【问题标题】:get the active route name from within a screen从屏幕中获取活动路线名称
【发布时间】:2022-01-04 10:21:00
【问题描述】:

我创建了一个堆栈导航器,我正在尝试根据当前屏幕路由名称进行 UI 更改,但是,当导航到另一个屏幕时,props.navigation.state 不会更新,我正在主屏幕内访问它:

useEffect(() => {
  console.log(navigation.state.routeName)
},[navigation])

注意我使用的是反应导航版本 4.4.1

【问题讨论】:

    标签: react-native react-navigation react-navigation-stack


    【解决方案1】:

    如果没有更多关于您在哪里调用 useEffect 的上下文很难回答,但您可以尝试添加一个焦点侦听器,如 react navigation 4.x 文档 (https://reactnavigation.org/docs/4.x/function-after-focusing-screen/) 中所引用的那样

    useEffect(() => {
     const focusListener = navigation.addListener('didFocus', () => {
       console.log(navigation.state.routeName)
     });
    
     return () => focusListener.remove()
    },[navigation])
    

    【讨论】:

      【解决方案2】:

      试试这个

      import {createAppContainer} from 'react-navigation';
      
      const getRootNavigation = () => createAppContainer(YourNavigator());
      
       render() {
          const RootNavigator = getRootNavigation();
          return (
            <View style={styles.container}>
              <RootNavigator
                onNavigationStateChange={(prev, next) =>
                  onNavigationStateChange(prev, next)
                }
              />
            </View>
          );
        }
      
      
      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;
      }
      
      function onNavigationStateChange(prevState, currentState) {
          const currentScreen = getCurrentRouteName(currentState);
        
        }
      }
      

      然后通过 mobx 或 redux 保存你的 currentScreen

      那么你可以在任何地方获取当前的屏幕名称。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-15
        • 1970-01-01
        • 2018-12-17
        • 2014-09-28
        • 1970-01-01
        • 2011-04-26
        • 2015-02-15
        • 2015-02-12
        相关资源
        最近更新 更多