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
相关产品推荐
相关产品推荐

