如何判断是否使用 ReactNavigation 导航到屏幕 [英] How can I tell if the screen is navigated to with ReactNavigation

查看:66
本文介绍了如何判断是否使用 ReactNavigation 导航到屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to refresh the data on the screen in a react native app whenever the screen appears - like in a ViewWillAppear method. I tried using the componentWillMount method but it looks like it fires once before it appears, and doesn't fire again when the view is navigated to again.

看这个例子 https://reactnavigation.org/docs/guides/screen-tracking,看起来我可以在根导航的 onNavigationStateChange 方法上添加一个侦听器,但我想将逻辑保留在屏幕中,因为如果我移动数据,它会变得混乱为根导航器之外的那个小块获取逻辑.

Looking at this example https://reactnavigation.org/docs/guides/screen-tracking, it looks like I can add a listener on the onNavigationStateChange method on the root navigation, but I'd like to keep the logic in the screen as it gets confusing if I move the data fetch logic for that one scree outside to the root navigator.

我尝试按照示例将该方法设置为我的堆栈导航,但它似乎没有触发.

I've tried to follow the example and set that method to my stacknavigation but it doesn't seem to trigger.

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

推荐答案

这里是我使用 onNavigateStateChange 的方法.

So here's how I did it using the 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);*/}
          }
        }}
      />

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

And in your screen you can check to see if your view will appear, note MyPage is the route name from your navigation object.

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

这篇关于如何判断是否使用 ReactNavigation 导航到屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆