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

React Native Navigation报错:undefined is not an object (evaluating 'this.props.navigation')

解决方案:undefined is not an object (evaluating 'this.props.navigation')

这个错误在React Native Navigation开发里真的太常见了,本质问题就是你的组件没有正确获取到导航上下文,下面分几种最常见的场景给你对应的解决办法:

1. 你的组件不是导航栈中的直接屏幕组件

如果你的组件是某个屏幕组件的子组件(不是直接在Stack.Screen/Tab.Screen里注册的页面),它不会自动拿到navigation props,这时候分组件类型处理:

函数组件方案:用useNavigation钩子

直接导入导航钩子,手动获取导航对象就行:

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

function MyChildComponent() {
  const navigation = useNavigation();

  const goToNextPage = () => {
    navigation.navigate('TargetScreen');
  };

  return <Button title="跳转至目标页" onPress={goToNextPage} />;
}

类组件方案:用withNavigation高阶组件

用高阶组件包裹你的类组件,自动注入导航props:

import { withNavigation } from '@react-navigation/compat';

class MyChildComponent extends React.Component {
  goToNextPage = () => {
    this.props.navigation.navigate('TargetScreen');
  };

  render() {
    return <Button title="跳转至目标页" onPress={this.goToNextPage} />;
  }
}

// 一定要用withNavigation包裹后再导出
export default withNavigation(MyChildComponent);

2. 组件没有被导航器正确包裹

首先要确保你的整个应用已经被NavigationContainer包裹,并且需要导航的屏幕组件是注册在导航栈内部的:

// App.js 正确配置示例
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        {/* 正确注册需要导航的屏幕 */}
        <Stack.Screen name="Home" component={HomeScreen} />
        <Stack.Screen name="TargetScreen" component={TargetScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

划重点:如果你的组件是在NavigationContainer外面渲染的,绝对拿不到导航上下文,所有需要导航功能的组件都要放在这个容器内部。

3. 使用React.memo或自定义高阶组件导致props丢失

如果你给组件加了React.memo或者自己写了高阶组件,可能会不小心过滤掉navigation props,这时候有两个选择:

  • 优先改用useNavigation钩子(不需要依赖props传递,更稳妥)
  • 或者在memo的比较函数里明确保留navigation的依赖:
const MemoizedComponent = React.memo(MyComponent, (prevProps, nextProps) => {
  // 确保navigation变化时组件会重新渲染
  return prevProps.navigation === nextProps.navigation;
});

4. 类组件的this绑定问题(少见但容易踩坑)

如果你的类组件里的点击事件没有正确绑定this,也会导致this.props变成undefined,这时候可以用箭头函数绑定:

// 方式1:用箭头函数定义方法
goToNextPage = () => {
  this.props.navigation.navigate('TargetScreen');
};

// 方式2:在render里手动绑定this
render() {
  return <Button title="跳转" onPress={this.goToNextPage.bind(this)} />;
}

建议先从第一种场景排查,绝大多数时候都是组件没在导航上下文里,或者子组件没正确获取导航对象~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:48:57