gpt4 book ai didi

reactjs - 当值来自 redux 并在子进程中更新时,React Navigation : How to update navigation title for parent,?

转载 作者:行者123 更新时间:2023-12-03 13:17:39 25 4
gpt4 key购买 nike

我正在使用react-navigation并有一个带有 ParentScreenChildScreen 的 StackNavigator。

两个屏幕都有相同的导航栏,其中包含来自 redux 的动态值。按照 Issue #313 中所述实现

这按预期工作。当我在 DetailScreen 中更新计数变量的值时,它也会更新导航栏中的值。

问题是,如果我返回父场景,导航栏中仍然有旧值。它不会更新为 redux 存储中的当前值。

child

screen shot 2017-04-11 at 15 20 28

家长(当我回去时)

screen shot 2017-04-11 at 15 21 31

子屏

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 : ''}`
};
}

有什么建议吗?

最佳答案

我的建议:

  1. 确保通过react-redux connect函数连接ParentScreen

  2. 如果您希望 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com