如何判断屏幕是否通过ReactNavigation导航到

Mon*_*key 6 react-native react-navigation

每当屏幕出现时,我都想在反应原生应用程序中刷新屏幕上的数据 - 就像在ViewWillAppear方法中一样.我尝试使用该componentWillMount方法,但看起来它在它出现之前触发一次,并且当视图再次导航时不会再次触发.

看看这个例子https://reactnavigation.org/docs/guides/screen-tracking,看起来我可以onNavigationStateChange在根导航上的方法上添加一个监听器,但我想将逻辑保留在屏幕上,因为它如果我将外部的一个scree的数据获取逻辑移到根导航器中,会让人感到困惑.

我试图按照示例将该方法设置为我的stacknavigation但它似乎没有触发.

  <RootNavigation ref={nav => { this.navigator = nav; }}
    onNavigationStateChange={(prevState, currentState, action) => {

      // maybe here I can fire redux event or something to let screens
      // know that they are getting focus - however it doesn't fire so
      // I might be implementing this incorrectly

      const currentScreen = getCurrentRouteName(currentState);
      const prevScreen = getCurrentRouteName(prevState);

      if (prevScreen !== currentScreen) {
        console.log('navigating to this screen', currentScreen);
      }
    }}
  />
Run Code Online (Sandbox Code Playgroud)

Mon*_*key 5

所以这就是我如何使用onNavigateStateChange.

      <RootNavigation
        ref={nav => { this.navigator = nav; }}
        uriPrefix={prefix}
        onNavigationStateChange={(prevState, currentState) => {
          const currentScreen = this.getCurrentRouteName(currentState);
          const prevScreen = this.getCurrentRouteName(prevState);
          if (prevScreen !== currentScreen) {
            this.props.emitActiveScreen(currentScreen);
            {/*console.log('onNavigationStateChange', currentScreen);*/}
          }
        }}
      />
Run Code Online (Sandbox Code Playgroud)

在您的屏幕中,您可以检查您的视图是否会出现,注意MyPage是导航对象中的路线名称。

  componentWillReceiveProps(nextProps) {
    if ((nextProps.activeScreen === 'MyPage' && nextProps.activeScreen !== this.props.activeScreen)) {
      // do your on view will appear logic here
    }
  }
Run Code Online (Sandbox Code Playgroud)

  • `emitActiveScreen` 代表什么?我在 https://github.com/react-community/react-navigation/search?utf8=%E2%9C%93&amp;q=emitActiveScreen&amp;type= 中搜索 `emitActiveScreen`,但这里一无所获 (7认同)