React Native类组件使用react-router-native传location.state报TypeError求助
解决react-router-native升级后Link传state目标组件无法获取location的问题
问题原因
升级react-router-native到v6及以上版本后,路由组件不再自动接收location、history等核心props,这就是你报错Cannot read property 'state' of undefined的根本原因——this.props.location已经不存在了。
解决方案
根据你的类组件场景,提供两种可行方案:
方案1:用withRouter高阶组件包裹类组件
react-router-native v6依然保留了withRouter,用来给类组件注入路由相关props:
- 补充导入
withRouter:
import { NativeRouter, Route, Link, Redirect, withRouter } from "react-router-native";
- 导出目标组件时用
withRouter包裹:
class SearchMethodComponent extends React.Component { componentDidMount() { console.log("Search method mounted") // 现在this.props.location可正常访问,建议加默认值避免解构报错 const { ingreds, more_needed, no_more_needed, initial_data } = this.props.location.state || {}; if (initial_data !== undefined) { this.setState({ initialData: initial_data, ingredients_rough: ingreds, moreNeeded: more_needed }) } else { this.setState({ ingredients_rough: ingreds, moreNeeded: more_needed }) } } // 其他组件逻辑... } // 关键步骤:用withRouter包裹后导出组件 export default withRouter(SearchMethodComponent);
方案2:重构为函数组件使用useLocation Hook
如果允许重构组件,函数组件的方式更贴合react-router v6的设计思路:
- 导入
useLocationHook:
import { useLocation, useEffect, useState } from "react-router-native";
- 在组件内获取location并处理逻辑:
function SearchMethodComponent() { const location = useLocation(); const [state, setState] = useState({ initialData: null, ingredients_rough: [], moreNeeded: false }); useEffect(() => { console.log("Search method mounted") const { ingreds, more_needed, no_more_needed, initial_data } = location.state || {}; if (initial_data !== undefined) { setState({ initialData: initial_data, ingredients_rough: ingreds, moreNeeded: more_needed }) } else { setState({ ingredients_rough: ingreds, moreNeeded: more_needed }) } }, []); // 其他组件逻辑... }
验证Link写法
你当前的Link写法符合v6规范,无需修改:
<Link to="/search-method/" state={{ ingreds: ingreds, more_needed: true }}>跳转</Link>
内容的提问来源于stack exchange,提问作者jem4789
相关产品推荐
相关产品推荐

