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

React不使用Hooks场景下类组件获取URL路由参数报错如何解决

问题原因

报错的核心诱因是withRouter导入语句错误:
你当前写的import { BrowserRouter as withRouter } from 'react-router-dom'逻辑是将路由根组件BrowserRouter取别名当做withRouter引入,实际使用的并不是官方提供的、用于注入路由属性的高阶组件withRouter,因此无法向Details类组件注入match/location/history等路由属性,还会引发组件初始化异常,抛出props相关的类型错误。

解决方法

适配react-router-dom v5及更早版本

  1. 修正withRouter的导入语句:
import { withRouter } from 'react-router-dom';
  1. 原有导出逻辑无需修改,保持如下写法即可:
export default withRouter(connect(mapStateToProps)(Details));
  1. 修正后原有获取参数的逻辑可正常运行:
const { questionId } = this.props.match.params;

适配react-router-dom v6版本

如果你的项目使用的是v6版本,该版本已官方移除withRouter高阶组件,你可以自行封装一个适配类组件的withRouter:

// 可直接在Details.js中定义,也可以放到公共工具文件中全局复用
import { useParams, useLocation, useNavigate } from 'react-router-dom';

function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    const location = useLocation();
    const navigate = useNavigate();
    const params = useParams();
    return <Component {...props} router={{ location, navigate, params }} />;
  }
  return ComponentWithRouterProp;
}

封装后组件内获取参数的写法调整为:

const { questionId } = this.props.router.params;

内容的提问来源于stack exchange,提问作者Qatr El-Nada

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:27:01