React Router 有很多种传递参数的方式,下面介绍其中两种常用的方式。
1. URL 参数
在 URL 中使用参数传递数据是 React Router 中最常用的一种方式,通过修改 URL 的 query 参数来传递数据。例如:
jsx
react router v6 文档
import { Link } from 'react-router-dom';
<Link to={{ pathname: '/user', search: '?name=john' }}>John</Link>
上面的代码中,通过 search 属性来传递参数,将参数以 key=value 的形式附加在 URL 中。
在接收参数的组件中可以通过 props.location.search 来获取参数,然后使用第三方库 query-string 解析参数。例如:
jsx
import queryString from 'query-string';
function User(props) {
  const name = queryString.parse(props.location.search).name;
  return <h1>Hello, {name}!</h1>;
}
2. 路由参数
另一种传递参数的方式是使用路由参数,在 URL 中使用冒号来表示参数,例如:
jsx
import { Link } from 'react-router-dom';
<Link to="/user/john">John</Link>
上面的代码中,/user/:name 中的 :name 表示参数。
在接收参数的组件中可以通过 props.match.params 来获取参数,例如:
jsx
function User(props) {
  const name = props.match.params.name;
  return <h1>Hello, {name}!</h1>;
}
以上是两种常用的传递参数的方式,当然还有其他的方式,例如使用 Redux 管理状态来传递参数等。