React Navigation: How to update navigation title for parent, when value comes from redux and gets updated in child?

别等时光非礼了梦想. 提交于 2019-12-03 06:47:37

My advice:

  1. Make sure that ParentScreen is connected through react-redux connect function.

  2. If you want the title of ParentScreen to get updated automatically when the state of the store changes, connecting it won't be enough. You will have to use the componentWillReceiveProps like you are doing in the ChildScreen Component.

Bonus: you could create a Higher Order Component for encapsulating that behaviour, like this:

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)
};

And then you could use it like this:

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

const ParentScreen = withTotalTitle(() => (
  <View>
    <Text>Whatever ParentScreen is supposed to render.</Text>
  </View>
));

OP, this is likely to be a problem with your redux implementation. Are you familiar with how redux implements its store? I see no mention here which means it is likely that your increment function is merely updating the child component's state instead of dispatching actions and reducers. Please have a look at a proper redux implementation like this one: https://onsen.io/blog/react-state-management-redux-store/

Have a common reducer for both parent and child. That way all the components(parent and child in your case) will get notified when the state changes.

Write a connect function for both parent and child. You'll receive the updated state in componentWillReceiveProps method. Use it as you please.

Hope it will help.

You need to use props in order to pass the incremented value from child to parent component.

find the article below. It has a great example of communications between parent and child components.

http://andrewhfarmer.com/component-communication/

Thanks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!