【问题标题】:Can I extract all the route keys of react-navigation?我可以提取 react-navigation 的所有路由键吗?
【发布时间】:2021-07-08 02:32:40
【问题描述】:

我正在尝试为所有屏幕制作一个键映射。 为此,我需要从react-navigation 的导航容器中提取所有键。

例如,

const result = {
   MainScreen: 'Main-p-u9s_rA3z5HCT-KHyDua',
   IndexScreen: 'Index-97mYyg2-P5Kb_wGY4E1ke',
   <RouteName>: <RouteKey>
   ...
}

有什么解决办法吗?

【问题讨论】:

    标签: react-native react-navigation react-navigation-v5


    【解决方案1】:

    你可以使用getRootState

    getRootState 方法返回一个导航状态对象,其中包含导航树中所有导航器的导航状态

    export const navigationRef = React.createRef();
    
    const App = () => {
      useEffect(() => {
        const navigationState = navigationRef.current?.getRootState();
    
        const result = {};
        navigationState.routes.forEach(route => {
          result[route.name] = route.key;
        });
        console.log(result);
      }, [navigationRef]);
      return (
        <NavigationContainer ref={navigationRef}>
          <Tab.Navigator>
            <Tab.Screen name="Screen1" component={Screen1} />
            <Tab.Screen name="Screen2" component={Screen2} />
            <Tab.Screen name="Screen3" component={Screen3} />
          </Tab.Navigator>
        </NavigationContainer>
      );
    };
    

    console.log(result) 在上面的代码中返回如下内容:

    {“Screen1”:“Screen1-AVVWEcCJjDeVeO3fu4tgb”,“Screen2”:“Screen2-nXoQ6xsdjKxoB4hbeXNou”,“Screen3”:“Screen3-FuFi77tfvex2QXZfin86s”}

    使用getRootState时请注意:

    ...如果当前没有呈现导航器,则返回的状态对象将是未定义的。

    也请看the navigation state reference

    【讨论】:

    • 如果有屏幕还没有渲染,这是否意味着它可能不在rootState?
    • 是的,如果导航器没有渲染,它就不会出现在导航状态对象中。这也适用于嵌套导航器。如果你有嵌套的导航器,你可能还需要更多的循环来获取result 对象中的这些路由,或者你可以在不使用getRootState 的情况下获得导航器的导航状态。无论哪种方式,我认为不可能一次得到所有东西。
    猜你喜欢
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2016-11-06
    • 1970-01-01
    • 2018-05-30
    • 2021-12-28
    相关资源
    最近更新 更多