在反应中使用 Link 将参数传递给另一个组件

passing parameter to another component using Link in react

我知道如果我需要调用另一个 component 那么我们需要像 <A x={y}/> 这样传递并且我们可以在 A.

中访问 props.x

但是这里我需要调用EditCertificate所以我需要将id传递给EditCertificate。但我在这里使用 Link 。我无法通过 id。当我访问它时,它即将到来 undefined.

<Link to={`/${props.certificate.id}/edit` }  >Edit</Link>

我正在调用此页面,如下所示。

<Route path ="/:id/edit" component={EditCertificate} ></Route>

如何在 EditCertificate 中访问 :id。当我访问它时,它给出了 undefined。我需要传递一些其他属性吗?

因为你使用的是 react-router,你可以简单地导入 useParams 钩子并在你的 EditCertificate 组件中获取 id

import { useParams } from 'react-router-dom'; 


const { id } = useParams(); // add inside your component body

由于EditCertificate直接由路由渲染:

<Route path ="/:id/edit" component={EditCertificate} />

route props 被传递给 EditCertificate。您只需要从 props 访问它们。

const { id } = props.match.params;

如果EditCertificate是一个class组件,那么显然是从this.props.

访问
const { id } = this.props.match.params;