react route如何传参数
React Router 传参方法
React Router 提供了多种传递参数的方式,适用于不同场景的需求。
路径参数(URL Params)
通过动态路由匹配传递参数,参数会显示在 URL 中。
// 路由配置
<Route path="/user/:id" component={User} />
// 组件跳转
<Link to="/user/123">User 123</Link>
// 或
history.push("/user/123");
// 获取参数
const { id } = useParams(); // React Router v6
// 或
const { id } = props.match.params; // React Router v5
查询参数(Query Params)
通过 URL 查询字符串传递参数,适合传递多个可选参数。
// 组件跳转
<Link to="/search?query=react&page=1">Search</Link>
// 或
history.push("/search?query=react&page=1");
// 获取参数
const [searchParams] = useSearchParams(); // React Router v6
const query = searchParams.get("query");
const page = searchParams.get("page");
// React Router v5 需要手动解析
const query = new URLSearchParams(props.location.search).get("query");
状态参数(State)
通过路由状态传递参数,参数不会显示在 URL 中,适合传递敏感或大量数据。
// 组件跳转
<Link to="/profile" state={{ userId: 123 }}>Profile</Link>
// 或
history.push("/profile", { userId: 123 });
// 获取参数
const { state } = useLocation(); // React Router v6
const userId = state?.userId;
// React Router v5
const userId = props.location.state?.userId;
自定义参数传递
可以通过组合方式传递复杂参数。
// 结合路径和状态
history.push({
pathname: "/edit/123",
state: { fromDashboard: true }
});
// 获取方式
const { id } = useParams();
const { state } = useLocation();
每种传参方式适用于不同场景:路径参数适合必要标识符,查询参数适合可选过滤条件,状态参数适合临时或敏感数据。根据具体需求选择最合适的方法。







