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

如何为React Navigation Error屏幕配置TypeScript自定义路由参数

解决TypeScript无法识别Error屏幕路由参数的问题

问题出在你的路由参数类型定义错误:NavigatorScreenParams是用于嵌套导航场景的类型,而你的Error是独立屏幕,不需要使用它,直接定义参数结构即可。

步骤1:修正路由参数类型定义

修改RootStackParamList中Error的类型,去掉多余的NavigatorScreenParams,直接指定参数结构:

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

export type RootStackParamList = {
  Root: undefined;
  // 直接定义Error屏幕的参数类型
  Error: {
    statusCode: number;
    description: string;
  } | undefined;
  Notifications: undefined;
  Log: undefined;
};

export type RootStackScreenProps<Screen extends keyof RootStackParamList> = NativeStackScreenProps<
  RootStackParamList,
  Screen
>;

// 若无需嵌套导航,可删除多余的ErrorParamList
// export type ErrorParamList = {
//   Error: {
//     statusCode: number;
//     description: string;
//   };
// };

如果想保留类型复用,也可以单独定义参数类型再引用:

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

// 单独定义Error屏幕的参数类型
export type ErrorScreenParams = {
  statusCode: number;
  description: string;
};

export type RootStackParamList = {
  Root: undefined;
  Error: ErrorScreenParams | undefined;
  Notifications: undefined;
  Log: undefined;
};

export type RootStackScreenProps<Screen extends keyof RootStackParamList> = NativeStackScreenProps<
  RootStackParamList,
  Screen
>;

步骤2:优化组件内参数获取(可选)

由于route.params可能为undefined,可以添加默认值避免潜在报错:

export default function ErrorScreen({ route, navigation }: RootStackScreenProps<'Error'>) {
  // 给参数设置默认值,处理params为undefined的情况
  const { statusCode = 500, description = '未知错误' } = route.params || {};
  
  const { setClientURL } = appState(({ setClientURL }) => ({
    setClientURL,
  }));
  // ...其他逻辑
}

原因说明

NavigatorScreenParams的作用是标记嵌套导航器的参数列表(比如TabNavigator作为Stack的某个屏幕时),你的Error是单个独立屏幕,使用这个类型会让TypeScript错误地将参数识别为嵌套导航的结构,而非你定义的statusCode和description。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 19:05:26