13

I'm using react-navigation and have a StackNavigator with a ParentScreen and a ChildScreen.

Both screens have the same navigation bar with a dynamic value from redux. Implemented like described in Issue #313

This works as expected. When I'm in DetailScreen and I update the value for the count variable, it also updates the value in the navigation bar.

Problem is, if I go back to the parent scene, there is still the old value in the navigation bar. It doesn't update to the current value in redux store.

Child

screen shot 2017-04-11 at 15 20 28

Parent (when I go back)

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

ParentScreen

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

Any advice?

4

4 回答 4

7

我的建议:

  1. 确保ParentScreen通过 react-reduxconnect功能连接。

  2. 如果您希望在ParentScreen商店状态更改时自动更新标题,仅连接它是不够的。您将不得不使用componentWillReceiveProps您在ChildScreen组件中所做的事情。

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

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>
));
于 2017-04-18T01:48:48.117 回答
2

父母和孩子都有一个共同的减速器。这样,所有组件(在您的情况下为父组件和子组件)都会在状态更改时收到通知。

为父母和孩子编写一个连接函数。您将在 componentWillReceiveProps 方法中收到更新的状态。随心所欲地使用它。

希望它会有所帮助。

于 2017-04-20T11:19:27.390 回答
2

OP,这可能是您的 redux 实现的问题。你熟悉 redux 是如何实现它的 store 的吗?我在这里没有看到任何提及,这意味着您的增量函数很可能只是更新子组件的状态,而不是调度动作和减速器。请看一个像这样的适当的 redux 实现:https ://onsen.io/blog/react-state-management-redux-store/

于 2017-04-20T00:00:37.490 回答
1

您需要使用道具才能将递增的值从子组件传递给父组件。

找到下面的文章。它有一个很好的父子组件之间通信的例子。

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

谢谢

于 2017-04-20T20:33:56.623 回答