react中link如何传参
在React中通过Link传递参数
使用react-router-dom的Link组件传递参数有多种方式,以下是常见的方法:
通过URL路径参数传递
在路由配置中定义动态参数,通过Link的to属性传递:
// 路由配置
<Route path="/user/:id" component={UserPage} />
// Link组件使用
<Link to="/user/123">用户页面</Link>
目标组件通过useParams获取参数:

import { useParams } from 'react-router-dom';
function UserPage() {
const { id } = useParams();
return <div>用户ID: {id}</div>;
}
通过查询字符串传递
使用URL的查询字符串格式传递参数:
<Link to="/search?query=react&page=1">搜索</Link>
目标组件通过useLocation获取:

import { useLocation } from 'react-router-dom';
function SearchPage() {
const location = useLocation();
const searchParams = new URLSearchParams(location.search);
const query = searchParams.get('query');
const page = searchParams.get('page');
}
通过state对象传递
可以传递不会显示在URL中的state数据:
<Link
to="/profile"
state={{
fromDashboard: true,
userData: { name: 'John' }
}}
>
个人资料
</Link>
目标组件通过useLocation获取state:
function ProfilePage() {
const location = useLocation();
const { fromDashboard, userData } = location.state;
}
组合使用多种方式
可以同时使用路径参数和state:
<Link
to="/products/42"
state={{ referrer: 'homepage' }}
>
产品详情
</Link>
注意事项
- 使用state传递时,参数不会出现在URL中,适合敏感或临时数据
- 刷新页面会丢失state传递的参数,除非配合持久化存储
- 路径参数适合作为资源标识,查询参数适合过滤和搜索条件






