reactrouterdomv6路由传参
时间: 2023-04-18 07:03:39 浏览: 65
React Router Dom v6 路由传参可以通过以下方式实现:
1. 使用 useParams() 钩子函数获取路由参数。
例如,定义一个路由 /user/:id,可以通过以下方式获取 id 参数:
```
import { useParams } from 'react-router-dom';
function User() {
const { id } = useParams();
return <h1>User {id}</h1>;
}
```
2. 使用 useLocation() 钩子函数获取查询参数。
例如,定义一个路由 /search?query=react,可以通过以下方式获取 query 参数:
```
import { useLocation } from 'react-router-dom';
function SearchResults() {
const location = useLocation();
const query = new URLSearchParams(location.search).get('query');
return <h1>Search results for {query}</h1>;
}
```
3. 使用 useHistory() 钩子函数实现编程式导航传参。
例如,从一个页面跳转到另一个页面,并传递参数:
```
import { useHistory } from 'react-router-dom';
function HomePage() {
const history = useHistory();
const handleClick = () => {
history.push('/user', { id: 123 });
};
return <button onClick={handleClick}>Go to User Page</button>;
}
function UserPage() {
const location = useLocation();
const { id } = location.state;
return <h1>User {id}</h1>;
}
```
以上是 React Router Dom v6 路由传参的几种方式,具体使用根据实际情况选择。