React Navigation:当值来自redux并在child中更新时,如何更新父级的导航标题?

cri*_*ken 12 reactjs react-native react-navigation

我正在使用react-navigation并且有一个带有 ParentScreen和ChildScreen的StackNavigator.

两个屏幕都具有相同的导航栏,其动态值来自redux.像问题#313中描述的那样实现

这按预期工作.当我在DetailScreen中并更新count变量的值时,它还会更新导航栏中的值.

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

儿童

屏幕截图2017-04-11 15 20 28

家长(当我回去时)

屏幕截图2017-04-11 at 15 21 31

ChildScreen

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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

ParentScreen

class ParentScreen extends Component {
  static navigationOptions = {
  title: ({ state }) => `Total: ${state.params && state.params.count ?    state.params.count : ''}`
  };
}
Run Code Online (Sandbox Code Playgroud)

有什么建议?

Jos*_*sep 7

我的建议:

  1. 确保ParentScreen通过react-redux connect功能连接.

  2. 如果您希望在ParentScreen商店状态发生变化时自动更新标题,则连接它将是不够的.您将必须使用componentWillReceiveProps您在ChildScreenComponent 中执行的操作.

额外:您可以创建一个更高阶组件来封装该行为,如下所示:

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)
};
Run Code Online (Sandbox Code Playgroud)

然后你可以像这样使用它:

const ChildScreen = withTotalTitle(({ increment }) => (
  <View>
    <Button onPress={() => increment()} title="Increment" />
  </View>
));

const ParentScreen = withTotalTitle(() => (
  <View>
    <Text>Whatever ParentScreen is supposed to render.</Text>
  </View>
));
Run Code Online (Sandbox Code Playgroud)