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

React-Navigation报错:Cannot read property 'routeName' of undefined求助

解决Cannot read property 'routeName' of undefined错误

这个错误的核心原因是你传入的路由名称和导航配置里的实际路由不匹配,加上可能的小疏漏,我来一步步帮你修复:

问题分析

你在CustomDrawer里调用navigateToScreen('Page1')、navigateToScreen('Page2')时传入的路由名称(Page1、Page2、Page3),在你的drawerNavigation配置中完全不存在——你的抽屉导航只配置了Home、MyCards、Profile等路由。react-navigation找不到对应的路由配置,就会抛出Cannot read property 'routeName' of undefined的错误。

另外还要确认你是否正确导入了NavigationActions,这也是常见的疏漏点。

修复步骤

1. 匹配路由名称

把CustomDrawer中的按钮文本和传入的路由名称改成drawerNavigation里已配置的项,比如:

// CustomDrawer.js 中的render部分修改
render () {
  return (
    <View style={styles.container}>
      <ScrollView>
        <View>
          <Text style={styles.sectionHeadingStyle}> Section 1 </Text>
          <View style={styles.navSectionStyle}>
            <Text style={styles.navItemStyle} onPress={this.navigateToScreen('Home')}> Home </Text>
          </View>
        </View>
        <View>
          <Text style={styles.sectionHeadingStyle}> Section 2 </Text>
          <View style={styles.navSectionStyle}>
            <Text style={styles.navItemStyle} onPress={this.navigateToScreen('MyCards')}> My Cards </Text>
            <Text style={styles.navItemStyle} onPress={this.navigateToScreen('Profile')}> Profile </Text>
          </View>
        </View>
      </ScrollView>
      <View style={styles.footerContainer}>
        <Text>This is my fixed footer</Text>
      </View>
    </View>
  );
}

2. 确保导入NavigationActions

在CustomDrawer.js的顶部添加导入语句:

import { NavigationActions } from 'react-navigation';

3. 可选优化:使用路由常量避免拼写错误

为了避免后续再出现类似的拼写问题,建议把所有路由名称抽成常量文件,比如:

// routes.js
export const ROUTES = {
  HOME: 'Home',
  MY_CARDS: 'MyCards',
  PROFILE: 'Profile',
  SEARCH_USERS: 'SearchUsers',
  // ...其他路由
};

然后在CustomDrawer.js和router.js中都使用这些常量,比如:

// CustomDrawer.js中调用
onPress={this.navigateToScreen(ROUTES.HOME)}
// router.js中配置
Home: { screen: Home },

这样就能彻底避免因拼写不一致导致的路由错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:47:49