React Native新手遇导航报错:undefined is not an object (evaluating 'this.props.navigation.navigate')
Hey there, I totally get how frustrating this must be—stuck on a navigation issue for a week is no fun! Let's break down why this is happening and fix it step by step.
问题根源
The error happens because your Swiper component isn't receiving the navigation prop from your StackNavigator. Navigation props are only automatically passed to the components directly registered as screens in your navigator (in your case, that's OnBoardingScreen and Home). Since Swiper is a child component of OnBoardingScreen, it doesn't get the navigation prop by default.
解决方案(两种方法任选其一)
方法1:手动传递navigation prop给Swiper
This is the simplest fix if you only need to pass the prop once.
- Go to your
OnBoardingScreencomponent (the one that rendersSwiper), and add thenavigationprop when you renderSwiper:
// Inside OnBoardingScreen's render method <Swiper navigation={this.props.navigation} />
Now your Swiper component will have access to this.props.navigation, and the home() method will work as expected.
方法2:使用withNavigation高阶组件
If you want to avoid manually passing the prop (especially if you use Swiper in multiple places), use the withNavigation HOC from react-navigation—it injects the navigation prop into any component, regardless of its position in the component tree.
- First, import
withNavigationat the top of yourswiper.jsfile:
import { withNavigation } from 'react-navigation';
- Change your component export line to wrap
SwiperwithwithNavigation:
// Replace the original export default line export default withNavigation(Swiper);
That's it! Now your Swiper component will automatically have access to this.props.navigation without needing to pass it manually.
额外小检查
I noticed you have two StackNavigator definitions in App.js (OnBoardingRoutes and LoginStack), but you're only using OnBoardingRoutes—that's totally fine, just wanted to make sure you intended that. Your initial route is set correctly to OnBoardingScreen, so that part is good.
内容的提问来源于stack exchange,提问作者vincent O

