如何在react-navigation中获取当前路由名称?

118
我想在react-navigation中获取当前路由或屏幕的名称,以便在if条件语句中使用并进行更改。

现在在react-navigation v5中如何实现呢? - Dimitri Kopriwa
4
React 版本间的变化太多了,非常混乱。文档中没有提到任何这些变化,代码也很难理解。我想知道人们是如何想出这些(旧)解决方案的。 - Kevin
有没有办法在 'wix/react-native-navigation' 中获取当前屏幕? - Vandit Mehta
35个回答

178

对于 react-navigation v5:

import { useRoute } from '@react-navigation/native';

const route = useRoute();
console.log(route.name);

5
你没有说明我应该在哪个地方使用useRoute()方法。我得到了“Hooks can only be called inside of the body of a function component(钩子只能在函数组件的主体内调用)”的错误提示。 - Aleksandrs
如何识别这种情况?直接导航到联系人屏幕。以及通过主屏幕导航到联系人屏幕。 - M.Kalidass
我该如何检查当前抽屉路由? - Areeb Vohra
1
同样适用于 react-navigation v6。 - chikabala
4
很好,但对于嵌套路由不起作用。 - AmerllicA
它还会在每次路由更改时触发重新渲染。只需要注意。 - David Novák

67

您可以按以下代码进行捕获:

this.props.navigation.state.routeName

这个答案适用于StackNavigator。之前的答案,this.props.activeItemKey不起作用。 - lucius degeer
在defaultNavigationOptions中,与Material Top Tab Navigator完美配合。 - CyberMew
我该如何在子堆栈中检查当前抽屉路由名称? - Areeb Vohra

33

如果您正在使用嵌套导航器,可以使用以下代码获取当前活动屏幕的状态

import { NavigationState } from 'react-navigation';

const getActiveRouteState = function (route: NavigationState): NavigationState {
    if (!route.routes || route.routes.length === 0 || route.index >= route.routes.length) {
        return route;
    }

    const childActiveRoute = route.routes[route.index] as NavigationState;
    return getActiveRouteState(childActiveRoute);
}

使用方法:

const activeRoute = getActiveRouteState(this.props.navigation.state);

当我需要从NavigationDrawer获取当前活动屏幕状态时,我使用这个。


3
这个答案我认为更加通用。 - chenop
你是如何将路由注入到自定义抽屉中的呢? - Sanchitos
导航状态(NavigationState)从哪里来? - Hugo
@Hugo NavigationState 是从 react-navigation 导入的。 - gianlucaparadise

19

在 react-navigation v5.x 中,这个很好用。

this.props.route.name

18
const routeNameRef = React.createRef();

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

    if (previousRouteName !== currentRouteName) {
      // Do something here with it
    }

    // Save the current route name for later comparision
    routeNameRef.current = currentRouteName
  }}
  >
  {/* ... */}
</NavigationContainer>
  );

export function getCurrentRouteName(action) {
  return routeNameRef;
}

您可以导入 getCurrentRouteName 函数并使用它来获取当前路由名称,这适用于 React Navigation 5 中的任何嵌套导航器。


1
小心这个陷阱。gotcha - Anand Rockzz

13

在使用 "react-navigation": "^3.0.8" 和 DrawerNavigator 时,可以通过 this.props.activeItemKeythis.props 对象中访问它。


使用DrawerNavigator可以实现,你是否在使用相同的组件? - Rishabh
1
如果您正在使用嵌套导航器,例如在DrawerNavigator中使用StackNavigator,并且需要在抽屉的contentComponent中获取activeItemKey,该如何实现? - cseelus
对于单个路由,这对我很有效,this.props.navigation.state.routeName。 - JHOAN B. HENRICHE

11
  import {getFocusedRouteNameFromRoute,useRoute} from '@react-navigation/native';

  //...
  const route = useRoute();
  const routeName = getFocusedRouteNameFromRoute(route); // Get Nested Route Name

route.name 也可以使用。 - Erkan GÖRGÜLÜ
route.name 对我不起作用,必须按照 oolala 建议的方式去做。 - BennKingy

11
在React Navigation v5中,我能够通过以下方法获取当前路由名称:
import { useNavigationState } from '@react-navigation/native'    

const routes = useNavigationState(state => state.routes)
const currentRoute = routes[routes.length - 1].name
console.log('currentRoute: ', currentRoute)

在使用此功能之前,请阅读相关文档:https://reactnavigation.org/docs/use-navigation-state/#how-is-usenavigationstate-different-from-navigationgetstate -> 最好使用 navigation.getState()。 - Wu Wei

10

准备工作

注册NavigationService.js,详细文档请查看没有导航属性的导航

<App
  ref={navigatorRef => {
        NavigationService.setTopLevelNavigator(navigatorRef);
  }}
/>

递归函数

function getCurrentRoute(nav){
    if(Array.isArray(nav.routes)&&nav.routes.length>0){
        return getCurrentRoute(nav.routes[nav.index])
    }else {
        return nav.routeName
    }
}

获取当前路由名称

getCurrentRoute(NavigationService.getNavigator().state.nav)

9

可以通过与导航容器附加的 navigationRef 来获取此内容,其中 navigationRef 是一个引用。

export const navigationRef = React.createRef()

<NavigationContainer
   ref={navigationRef} 
   >
  <Navigator />
</NavigationContainer>

然后使用: const currentRouteName = navigationRef.current.getCurrentRoute().name

或者在函数式组件中,您可以使用useRef:const navigationRef = React.useRef()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接