如何在app.js的通知处理器中使用useRoute获取当前屏幕名称
问题原因
你这种写法违反了React Hook的使用规则:useRoute 仅允许在React函数组件的顶层作用域、或者自定义Hook内部调用。通知处理器是独立的回调函数,运行时不在组件渲染生命周期内,无法拿到组件上下文的路由信息,必然无法正常输出路由名称。
解决方案
以下两种是生产环境常用的可行方案,你可以根据现有项目结构选择:
方案1:使用React Navigation官方提供的导航Ref获取当前路由
这是官方推荐的「在组件外部获取路由/导航实例」的方案,无需额外引入状态管理:
- 首先在你的根导航组件处创建并绑定导航Ref
// 根文件(一般是App.js)导入依赖 import { NavigationContainer, createNavigationContainerRef } from '@react-navigation/native'; // 创建全局导航Ref export const navigationRef = createNavigationContainerRef(); // 给NavigationContainer绑定ref function App() { return ( <NavigationContainer ref={navigationRef}> {/* 你原有的导航栈配置 */} </NavigationContainer> ) }
- 修改通知处理器代码,用Ref获取当前路由
// 导入刚才定义的navigationRef import { navigationRef } from './App'; Notifications.setNotificationHandler({ handleNotification: (n) => { const { keeperId, type } = n?.request?.content?.data ?? {}; // 替换useRoute调用 const currentRoute = navigationRef.getCurrentRoute(); console.log('route name'); console.log(currentRoute?.name); const showNotification = keeperId === store.getState().chat.chat.keeperUserId; // 原代码冗余,无需用new Promise包裹,直接返回resolve即可 return Promise.resolve({ shouldShowAlert: showNotification, shouldPlaySound: false, shouldSetBadge: false, }); }, });
注意:调用
getCurrentRoute时要确保导航已经完成初始化,代码里加可选链?.可以避免空值报错。
方案2:将路由名称存在全局状态中(适配你已经用Redux的场景)
你当前已经在从Redux Store取数据,可以直接把路由名称同步到Store里,随时取用:
- 在Redux中新增一个存储当前路由名称的字段,比如
app.currentRouteName,新增对应的更新Action - 在导航容器上监听路由变化,同步更新Store
<NavigationContainer ref={navigationRef} onStateChange={() => { const currentRoute = navigationRef.getCurrentRoute(); if (currentRoute) { // dispatch action更新Store里的路由名称 store.dispatch({ type: 'SET_CURRENT_ROUTE_NAME', payload: currentRoute.name }) } }} > {/* 原有导航配置 */} </NavigationContainer>
- 通知处理器里直接从Store取路由名称即可
const currentRouteName = store.getState().app.currentRouteName; console.log(currentRouteName);
内容的提问来源于stack exchange,提问作者Julio Palacios
相关产品推荐
相关产品推荐

