我正在使用react-navigation并有一个带有 ParentScreen 和 ChildScreen 的 StackNavigator。
两个屏幕都有相同的导航栏,其中包含来自 redux 的动态值。按照 Issue #313 中所述实现
这按预期工作。当我在 DetailScreen 中更新计数变量的值时,它也会更新导航栏中的值。
问题是,如果我返回父场景,导航栏中仍然有旧值。它不会更新为 redux 存储中的当前值。
child
家长(当我回去时)
子屏
class ChildScreen extends Component {
static navigationOptions = {
title: ({ state }) => `Total: ${state.params && state.params.count ? state.params.count : ''}`
};
componentWillReceiveProps(nextProps) {
if (nextProps.count != this.props.count) {
this.props.navigation.setParams({ count: nextProps.count });
}
}
render() {
return (
<View>
<Button onPress={() => this.props.increment()} title="Increment" />
</View>
);
}
}
家长屏幕
class ParentScreen extends Component {
static navigationOptions = {
title: ({ state }) => `Total: ${state.params && state.params.count ? state.params.count : ''}`
};
}
有什么建议吗?
最佳答案
我的建议:
确保通过react-redux
connect
函数连接ParentScreen
。如果您希望
ParentScreen
的标题在商店状态发生变化时自动更新,仅连接它是不够的。您必须像在ChildScreen
组件中一样使用componentWillReceiveProps
。
奖励:您可以创建一个高阶组件来封装该行为,如下所示:
const withTotalTitle = Component => props => {
class TotalTitle extends Component {
static navigationOptions = {
title: ({ state }) => `Total: ${state.params && state.params.count ? state.params.count : ''}`
};
componentWillReceiveProps(nextProps) {
if (nextProps.count != this.props.count) {
this.props.navigation.setParams({ count: nextProps.count });
}
}
render() {
return (
<Component {...props}/>
);
}
}
return connect(state => { count: state.total })(TotalTitle); // update this (I have no idea what the structure your state looks like)
};
然后你可以像这样使用它:
const ChildScreen = withTotalTitle(({ increment }) => (
<View>
<Button onPress={() => increment()} title="Increment" />
</View>
));
const ParentScreen = withTotalTitle(() => (
<View>
<Text>Whatever ParentScreen is supposed to render.</Text>
</View>
));
关于reactjs - 当值来自 redux 并在子进程中更新时,React Navigation : How to update navigation title for parent,?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43347536/