我可以提取反应导航的所有路由键吗?

Can I extract all the route keys of react-navigation?

我正在尝试为所有屏幕制作一个按键映射。 为此,我需要从 react-navigation.

的导航容器中提取所有键

例如,

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

有解决办法吗?

你可以使用 getRootState.

The getRootState method returns a navigation state object containing the navigation states for all navigators in the navigation tree

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) 在上面的代码中 returns 是这样的:

{"Screen1": "Screen1-AVVWEcCJjDeVeO3fu4tgb", "Screen2": "Screen2-nXoQ6xsdjKxoB4hbeXNou", "Screen3": "Screen3-FuFi77tfvex2QXZfin86s"}

使用时请注意getRootState:

...the returned state object will be undefined if there are no navigators currently rendered.

另请参阅the navigation state reference