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

React开发路由跳转传id,读取时报无法读取undefined的params属性错误

动态路由参数读取报错:TypeError: Cannot read property 'params' of undefined

现有实现逻辑

  • 列表页跳转逻辑(list.js 片段):引入 react-router-dom 的 Link 组件,通过动态拼接路径生成编辑页跳转入口
import { Link } from "react-router-dom";
<Link to={`/edit/${item.id}`} > Edit </Link>
  • 编辑页组件逻辑(edit.js 片段):引入 Link、useHistory 钩子,尝试通过组件props读取路由传入的动态id值
import { Link, useHistory } from "react-router-dom";
const Edit = (props) => {
  const history = useHistory();
  // 报错触发行
  const currentCatId = props.match.params.id;
} 
export default Edit;

报错根因

报错触发点为 props.match.params.id 这行代码,从报错信息可知,props对象存在,但props.match字段为undefined,因此进一步读取其下的params属性时触发异常。
常见触发场景有两类:

  • 项目使用 react-router-dom v6 版本,该版本不再通过组件props自动向路由组件注入match、location这类路由属性,因此props上根本不存在match字段
  • 项目使用v5版本,但Edit组件没有直接被<Route>组件匹配渲染,而是经过自定义组件嵌套转发,导致路由的props自动注入逻辑失效,props本身不携带match字段

修复方案

  1. 适配 react-router-dom v6 版本
    不再依赖props获取路由参数,改用内置的useParams钩子直接读取动态路由参数,替换原有的props读取逻辑:
    import { Link, useNavigate, useParams } from "react-router-dom";
    const Edit = () => {
      const navigate = useNavigate();
      // 直接从钩子解构获取动态路由id
      const { id: currentCatId } = useParams();
    } 
    export default Edit;
    
    注:v6 版本中原先的useHistory钩子已替换为useNavigate,可根据实际业务逻辑调整跳转方法
  2. 适配 react-router-dom v5 版本
    优先确保Edit组件被<Route path="/edit/:id" component={Edit}>直接匹配渲染,让路由完成props自动注入;如果组件是嵌套渲染的场景,可引入useRouteMatch钩子在组件内部直接获取match对象,不依赖外部传入的props:
    import { Link, useHistory, useRouteMatch } from "react-router-dom";
    const Edit = () => {
      const history = useHistory();
      const match = useRouteMatch("/edit/:id");
      const currentCatId = match.params.id;
    } 
    export default Edit;
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 13:36:03