1

更改屏幕执行时我需要一个函数,我的意思是当从屏幕主页导航到执行回调函数的关于屏幕时。

设想

我想在更改任何导航运行回调函数以进行某些检查时创建全局堆栈,例如(用户令牌、互联网状态、检查位置是一个或关闭等

尝试这个

我为Stack-navigation和implemnet创建了一个类组件UNSAFE_componentWillUpdate,可以检测到任何导航。

代码

UNSAFE_componentWillUpdate(prevProp, prevState) {
    if (prevProp != this.props) {
      console.log('change state navigation');
    }
  }

就这样误会

  • 无法检测到第一个屏幕index-zero 主屏幕
  • 我必须为每个堆栈编写此代码。

我的堆栈

<Stack.Navigator>
    <Stack.Screen
      name="Home"
      component={Home}
    />
   <Stack.Screen
      name="About"
      component={About}
    />
</Stack.Navigator>
4

1 回答 1

0

您可以在“NavigationContainer”中使用“onNavigationStateChange”道具获取当前路线

反应导航 4.x

onNavigationStateChange={(prevState, currentState) => {
    const currentScreen = this.getCurrentRouteName(currentState);
    const prevScreen = this.getCurrentRouteName(prevState);
}}

// gets the current screen from navigation state
function getCurrentRouteName(navigationState) {
  if (!navigationState) {
    return null;
  }
  const route = navigationState.routes[navigationState.index];
  // dive into nested navigators
  if (route.routes) {
    return getCurrentRouteName(route);
  }
  return route.routeName;
}

反应导航 5.x

<NavigationContainer
      ref={navigationRef}
      onReady={() => routeNameRef.current = navigationRef.current.getCurrentRoute().name}
      onStateChange={() => {
        const previousRouteName = routeNameRef.current;
        const currentRouteName = navigationRef.current.getCurrentRoute().name

        if (previousRouteName !== currentRouteName) {
          // The line below uses the expo-firebase-analytics tracker
          // https://docs.expo.io/versions/latest/sdk/firebase-analytics/
          // Change this line to use another Mobile analytics SDK
          Analytics.setCurrentScreen(currentRouteName);
        }

        // Save the current route name for later comparision
        routeNameRef.current = currentRouteName;
      }}
 >
   {/* ... */}
 </NavigationContainer>
于 2020-10-20T06:01:14.400 回答