繁体   English   中英

react-native中屏幕变化时如何实现回调函数?

[英]How to implement callBack function when screen change in react-native?

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

设想

我想在更改任何 naviagte run 回调函数以进行某些检查时创建全局堆栈,例如( userToken、internet 状态、检查位置是 1 或关闭等

尝试这个

我为堆栈导航和实现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>

您可以使用“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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM