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

React Native使用React Navigation报错route is undefined问题求助

错误排查与修复方案

你遇到的route is undefined报错可通过以下几个步骤逐一排查修复:

  • 组件未正确返回JSX:你定义的Home、Profile组件使用大括号包裹逻辑但没有显式returnJSX内容,相当于返回undefined,会导致导航渲染异常触发路由相关报错。可以给组件补充return语句,或者直接用简写的箭头函数写法省略大括号。
  • 缺少核心组件导入:代码中使用了Text组件但没有从react-native包导入,未定义的组件会连带触发导航渲染失败,需补充Text的导入语句。
  • 依赖安装不完整:React Navigation运行需要额外的原生依赖,仅安装导航核心包会导致运行时报错,需确保你已经安装了所有必须依赖:
    原生RN项目执行:
    npm install react-native-screens react-native-safe-area-context
    
    Expo项目执行:
    expo install react-native-screens react-native-safe-area-context
    
    安装完成后需要重新构建整个应用,不能仅刷新JS bundle。
  • 子组件未正确接收route参数:如果你在页面组件内部调用了route相关的属性(比如route.params),需要从组件的props中显式解构route,例如const Home = ({ route }) => {...},直接调用未定义的route变量会直接抛出该报错。

修正后的完整代码

import { Text } from 'react-native';
import { createStackNavigator } from "@react-navigation/stack";
import { NavigationContainer } from "@react-navigation/native";

const Stack = createStackNavigator();

// 补充return语句返回JSX
const Home = () => {
  return <Text>Home</Text>;
};

const Profile = () => {
  return <Text>Profile</Text>;
};

export default function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={Home} />
        <Stack.Screen name="Profile" component={Profile} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

验证步骤

修改代码后执行缓存清理重启项目即可:

  • Expo项目:执行expo start -c启动
  • 原生RN项目:先执行npx react-native start --reset-cache,再新开终端执行对应平台的启动命令运行应用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 08:36:03