You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在app.js的通知处理器中使用useRoute获取当前屏幕名称

问题原因

你这种写法违反了React Hook的使用规则:useRoute 仅允许在React函数组件的顶层作用域、或者自定义Hook内部调用。通知处理器是独立的回调函数,运行时不在组件渲染生命周期内,无法拿到组件上下文的路由信息,必然无法正常输出路由名称。

解决方案

以下两种是生产环境常用的可行方案,你可以根据现有项目结构选择:

方案1:使用React Navigation官方提供的导航Ref获取当前路由

这是官方推荐的「在组件外部获取路由/导航实例」的方案,无需额外引入状态管理:

  1. 首先在你的根导航组件处创建并绑定导航Ref
// 根文件(一般是App.js)导入依赖
import { NavigationContainer, createNavigationContainerRef } from '@react-navigation/native';

// 创建全局导航Ref
export const navigationRef = createNavigationContainerRef();

// 给NavigationContainer绑定ref
function App() {
  return (
    <NavigationContainer ref={navigationRef}>
      {/* 你原有的导航栈配置 */}
    </NavigationContainer>
  )
}
  1. 修改通知处理器代码,用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里,随时取用:

  1. 在Redux中新增一个存储当前路由名称的字段,比如app.currentRouteName,新增对应的更新Action
  2. 在导航容器上监听路由变化,同步更新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>
  1. 通知处理器里直接从Store取路由名称即可
const currentRouteName = store.getState().app.currentRouteName;
console.log(currentRouteName);

内容的提问来源于stack exchange,提问作者Julio Palacios

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 07:18:01