react-router-native点击Link报错:undefined is not an object (evaluating '_this.context.router.history')
解决React Router Native中跳转时的
undefined is not an object (evaluating '_this.context.router.history')错误 这个错误的根源非常明确——你把<Link>组件放在了<NativeRouter>的外部了!
React Router的所有路由相关组件(比如<Link>、useNavigate钩子等)都依赖于Router提供的上下文(Context)来获取路由实例(比如history对象)。如果你的<Link>不在<NativeRouter>包裹的范围内,它根本拿不到router上下文,自然就会抛出“找不到_this.context.router.history”的错误。
看你贴出的代码结构:
<Left> <Link to="/menu"> <Image source={require("./src/assets/images/home.png")} style={styles.homeIcon} /> </Link> </Left> ... <NativeRouter> <Container> <Stack> <Route exact path="/" component={Login} /> <Route path="/menu" component={() => <Menu showMenuIcon={this.showMenuIcon} />} /> <Route path="/dialog" component={() => <Dialog showMenuIcon={this.showMenuIcon} />} /> ... </Stack> </Container> </NativeRouter>
你写的<Link>完全在<NativeRouter>标签的外面,不在路由上下文覆盖的区域里,这就是问题所在。
解决方法很简单:
把包含<Link>的<Left>组件移动到<NativeRouter>内部,确保所有需要使用路由功能的组件都被Router包裹。调整后的结构大概是这样:
<NativeRouter> <Left> <Link to="/menu"> <Image source={require("./src/assets/images/home.png")} style={styles.homeIcon} /> </Link> </Left> <Container> <Stack> <Route exact path="/" component={Login} /> <Route path="/menu" component={() => <Menu showMenuIcon={this.showMenuIcon} />} /> <Route path="/dialog" component={() => <Dialog showMenuIcon={this.showMenuIcon} />} /> ... </Stack> </Container> </NativeRouter>
如果<Left>是某个全局布局组件的一部分,那整个布局组件都应该放在<NativeRouter>里面,这样它的所有子组件才能正常访问路由上下文。
内容的提问来源于stack exchange,提问作者kutirie
相关产品推荐
相关产品推荐

