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

React中通过Link跳转路由时如何向目标组件传递并获取id参数

你拿到undefined的核心原因是路由路径参数不会直接作为组件的顶层props暴露,需要通过React Router提供的专用API获取,具体写法和你使用的React Router版本强相关:

排查前置步骤

先确认跳转后浏览器地址栏的路径是否符合预期,比如是否为/123/edit的格式,如果路径里的id本身就是空的,先检查props.certificate.id是否有有效值。

不同版本的获取方式

1. React Router v5 版本

你用component属性关联路由组件时,框架会自动给组件注入match/location/history三个路由相关props,路径参数存放在match.params下:

// 函数组件
function EditCertificate(props) {
  const id = props.match.params.id
  // 你的业务逻辑
}

// 类组件
class EditCertificate extends React.Component {
  render() {
    const id = this.props.match.params.id
    // 你的业务逻辑
  }
}

2. React Router v6 版本(最常见的undefined原因)

v6版本不再自动给组件注入路由props,需要用内置Hook获取参数:

  • 函数组件直接用useParams Hook:
import { useParams } from 'react-router-dom'

function EditCertificate() {
  // 解构变量名必须和路由path里定义的参数名完全一致,这里路由写的是:id,所以解构id
  const { id } = useParams()
  // 注意:useParams返回的参数都是字符串类型,需要数字的话自行转换:const id = Number(useParams().id)
  // 你的业务逻辑
}
  • 类组件需要自行封装高阶组件传递路由参数:
// 先封装withRouter高阶组件
import { useParams, useLocation, useNavigate } from 'react-router-dom'

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

// 包裹你的类组件
class EditCertificate extends React.Component {
  render() {
    const id = this.props.router.params.id
    // 你的业务逻辑
  }
}
export default withRouter(EditCertificate)

不需要修改你现有的Link和Route配置,按以上方式获取参数即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 11:36:06