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

标签 reactjs react-native react-navigation

我正在使用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/

相关文章:

javascript - 为什么我们使用 () => [] 而不是 []?

android - 在 React Native 中获取设备 ID?

react-native - 登录后带有顶部选项卡的抽屉导航

reactjs - 没有 React-Native 或 React-Navigation 的 React 深度链接

svg - 使用 React 创建交互式 SVG 组件

reactjs - 使用 Async/Await 进行 native 调试

ios - 使用自定义 xcode 构建配置找不到“React/RCTBundleURLProvider.h”文件

javascript - 如何在 react 导航5中定义屏幕内的自定义标题?

javascript - react : How to access array in an object?

javascript - React 中的父函数中未调用 Set State