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

React Router使用props.match.params.id报params未定义错误如何解决

问题原因

你当前使用的是React Router v6版本,该版本已经移除了组件props上的match属性,所以读取params时会报undefined错误。

解决方法

有两种常用实现方案,优先推荐第一种:

  • 方案1:使用useParams Hook获取路由参数
    直接在ProductDetails组件中引入useParams Hook即可,修改后代码如下:
import { useParams } from 'react-router-dom';

const ProductDetails = () => {
  // 直接解构获取路径中定义的id参数
  const { id } = useParams();

  return (
    <div>
      <h1> {id} </h1>
    </div>
  );
};
  • 方案2:自定义高阶组件适配旧写法(仅适用于v5升级的存量项目)
    如果项目是从v5版本升级上来,不想改动原有组件的props读取逻辑,可以自行实现withRouter高阶组件封装:
// 先实现withRouter高阶组件
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 ProductDetails = withRouter((props) => {
  const id = props.router.params.id
  return (
    <div>
      <h1> {id} </h1>
    </div>
  );
});

内容的提问来源于stack exchange,提问作者Saye

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 19:15:03