React Router用Link传递state,访问时出现state undefined TypeError如何解决
问题原因
报错本质是NextPage组件没有拿到React Router注入的路由属性,所以props.location为undefined,读取state时触发类型错误。不同版本的React Router解决方案不同:
React Router v5 解决方案
你当前写的Route写法不会自动给组件注入路由属性,可选三种修改方式:
- 方式1:改用
component属性指定路由组件,Route会自动注入路由属性
<Route exact path="/job-run-id/:jobID" component={NextPage} />
- 方式2:用
render属性手动透传路由属性,适合需要给组件传额外自定义参数的场景
<Route exact path="/job-run-id/:jobID" render={(routeProps) => <NextPage {...routeProps} />} />
- 方式3:不修改Route配置,给
NextPage包裹withRouter高阶组件注入路由属性
import { withRouter } from 'react-router-dom'; const NextPage = (props) => ( <div> <p>previous path is: {props.location.state.prevPath}</p> </div> ); export default withRouter(NextPage);
React Router v6 解决方案
v6版本移除了Route的component、render属性,也取消了withRouter高阶组件,需要用hooks获取路由属性:
- 保持你的Route配置写法不变(v6用
element属性指定组件) - 在
NextPage中使用useLocation钩子获取location对象
import { useLocation } from 'react-router-dom'; const NextPage = () => { const location = useLocation(); return ( <div> <p>previous path is: {location.state?.prevPath}</p> </div> ); };
额外注意
如果用户直接通过地址栏输入url访问NextPage,没有通过Link跳转的话,state属性会不存在,建议添加可选链?.或者默认值兜底,避免再次触发报错。
内容的提问来源于stack exchange,提问作者ArthurJ
相关产品推荐
相关产品推荐

