如何在navigation.js文件中的react-navigation中获取当前路线名称?
我想知道当前的路由名称,但在导航 js 文件中,我在任何组件中使用 useRoute 钩子并且工作良好,但是当我在 navigation.js 中使用 useRoute 时出现此错误
错误:无法找到路由对象。您的组件是否位于导航器屏幕内?
navigation.js 代码示例,
export default function Navigation() {
const route = useRoute(); // show error >> Error: Couldn't find a route object. Is your component inside a screen in a navigator?
return (
<Stack.Navigator
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="HomeScreen" component={HomeScreen} />
</Stack.Navigator>
);
}
当我删除 useRoute 时,错误消失了,但我需要使用 useRoute 或任何其他方式来获取 navigation.js 文件中的当前路由名称。
I want to know the current route name but inside the navigation js file, I use the useRoute hook in any component and work well, but I get this error when I use useRoute inside navigation.js
Error: Couldn't find a route object. Is your component inside a screen in a navigator?
navigation.js code example,
export default function Navigation() {
const route = useRoute(); // show error >> Error: Couldn't find a route object. Is your component inside a screen in a navigator?
return (
<Stack.Navigator
screenOptions={{
headerShown: false,
}}>
<Stack.Screen name="HomeScreen" component={HomeScreen} />
</Stack.Navigator>
);
}
when I remove useRoute, the Error is gone, But I need to use useRoute or any other way to get current route name inside navigation.js file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 v6 中完美运行。
在您的堆栈中,您必须通过以下方式将组件转换为子组件:
Works perfectly in v6.
In Your Stack, you have to convert the component to child.. in this way:
您可以将
navigationContainerRef
从NavigationContainer
传递到Navigation
组件,以使navigation
对象可访问。考虑以下代码片段。
然后,在
Navigation
内。然后使用
route?.name
访问当前路由名称。编辑:正如 jhon antoy 在评论中正确指出的那样,如果我们导航到不同的屏幕,这不会更新当前的路线状态。我们需要自己更新它,如下所示。
在
导航
内。我做了一个带有一些简单导航按钮的小吃。
You can pass the
navigationContainerRef
from theNavigationContainer
to theNavigation
comomponent to make thenavigation
object accessible.Consider the following code snippet.
Then, inside
Navigation
.The current route name get then be accessed using
route?.name
.Edit: As jhon antoy correctly pointed out in the comments, this does not update the current route state if we navigate to a different screen. We need to update this ourselves as follows.
Inside
Navigation
.I have made a snack with some simple navigation buttons.