You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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获取路由属性:

  1. 保持你的Route配置写法不变(v6用element属性指定组件)
  2. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 07:39:02