react路由如何带多个参数
在React路由中传递多个参数
React Router提供了多种方式传递多个参数,可以通过路径参数、查询参数或状态传递。以下是常见方法:
使用路径参数(URL参数)
在路由配置中定义多个参数占位符,通过冒号:标记参数名:
<Route path="/user/:id/:name" component={UserComponent} />
组件中通过useParams获取参数:
import { useParams } from 'react-router-dom';
function UserComponent() {
const { id, name } = useParams();
return <div>ID: {id}, Name: {name}</div>;
}
使用查询参数(URLSearchParams)
通过?后的键值对传递参数:

<Link to="/search?q=react&page=2">Search</Link>
组件中使用useSearchParams获取:
import { useSearchParams } from 'react-router-dom';
function SearchComponent() {
const [searchParams] = useSearchParams();
const q = searchParams.get('q');
const page = searchParams.get('page');
return <div>Query: {q}, Page: {page}</div>;
}
使用状态对象传递
通过state属性传递复杂对象:
<Link
to="/profile"
state={{
userId: 123,
fromDashboard: true
}}
>
Profile
</Link>
组件中使用useLocation获取:

import { useLocation } from 'react-router-dom';
function Profile() {
const { state } = useLocation();
return <div>User ID: {state.userId}</div>;
}
组合使用多种方式
可以同时使用路径参数和查询参数:
<Route path="/product/:id" component={Product} />
// 导航到
<Link to="/product/123?color=red&size=large">Product</Link>
组件中同时获取:
function Product() {
const { id } = useParams();
const [searchParams] = useSearchParams();
const color = searchParams.get('color');
const size = searchParams.get('size');
// ...
}
动态生成带参数的路由链接
使用模板字符串动态生成路径:
const userId = 456;
const userName = 'john';
<Link to={`/user/${userId}/${userName}`}>User</Link>
注意事项
- 路径参数适合必选参数,查询参数适合可选参数
- 状态对象不会显示在URL中,适合敏感数据或临时数据
- 在React Router v6中必须使用指定的hooks获取参数
- 参数值会被转换为字符串,复杂对象需要序列化






