在单页面应用(SPA)的开发中,路由是必不可少的。React Router 是一个流行的路由库,它可以方便地管理应用的路由。在实际开发中,我们经常需要在路由之间传递参数,比如用户 ID、商品 ID 等等。本文将介绍在 React Router 中实现路由传参的方法,并提供示例代码。
基本用法
在 React Router 中,可以通过 <Route> 组件的 path 属性来定义路由。例如:
<Route path="/user/:id" component={User} />这个路由的路径是 /user/:id,其中 :id 是一个参数,表示用户 ID。当用户访问 /user/123 时,React Router 会将参数 123 传递给 User 组件。在 User 组件中,可以通过 props.match.params.id 来获取参数。
function User(props) {
const userId = props.match.params.id;
// ...
}这是 React Router 中最基本的路由传参的方法。但是,在实际开发中,我们可能需要更复杂的路由传参方式,下面将介绍两种常见的方法。
Query 参数
Query 参数是一种常见的路由传参方式,它可以在 URL 中通过 ? 来传递参数。例如:
/user?id=123&name=Tom
在 React Router 中,可以通过 location 对象的 search 属性来获取 URL 中的查询字符串。例如:
function User(props) {
const search = props.location.search;
const params = new URLSearchParams(search);
const userId = params.get('id');
const userName = params.get('name');
// ...
}这里使用了 URLSearchParams 对象来解析查询字符串。注意,URLSearchParams 是一个比较新的 API,如果需要兼容旧版本浏览器,可以使用第三方库 query-string。
在使用 Query 参数时,需要注意以下几点:
- URL 中的查询字符串应该经过编码,否则可能会导致解析错误。
- 查询字符串中的参数可以重复出现,例如
/user?id=123&id=456。 - 查询字符串中的参数可以是数组,例如
/user?tags[]=a&tags[]=b。
State 参数
State 参数是一种不常用但很实用的路由传参方式,它可以通过 location 对象的 state 属性来传递状态。例如:
<Link to={{
pathname: '/user',
state: {
id: 123,
name: 'Tom'
}
}}>User</Link>在 React Router 中,可以通过 location 对象的 state 属性来获取状态。例如:
function User(props) {
const state = props.location.state;
const userId = state.id;
const userName = state.name;
// ...
}使用 State 参数时,需要注意以下几点:
- State 参数只在当前页面有效,刷新页面后会丢失。
- State 参数不应该包含敏感信息,因为它们可能会被浏览器记录在历史记录中。
示例代码
下面是一个完整的示例代码,演示了如何在 React Router 中实现路由传参。
-- -------------------- ---- -------
------ ----- ---- --------
------ - ------------- -- ------- ------ ---- - ---- -------------------
-------- ------ -
------ -
-----
-------------
----
--------- ------------------- ---------------
--------- ------------------------------- ---------------
--------- -----
--------- --------
------ -
--- ----
----- -------
-
------- -----------------
-----
------
--
-
-------- ----------- -
----- ------ - ----------------------
----- ------ - --- ------------------------
----- ------ - --------------------- -- -----------------
----- -------- - ------------------ -- ---------------------------
------ -
-----
-------- -------------
-------- --------------
------
--
-
-------- ----- -
------ -
--------
------ -------- ----- ---------------- --
------ ---------------- ---------------- --
------ ------------ ---------------- --
---------
--
-
------ ------- ----在这个示例中,我们定义了三个链接,分别演示了通过 URL 参数、Query 参数和 State 参数来传递参数。在 User 组件中,我们通过 props.match.params.id、props.location.search 和 props.location.state 来获取参数。注意,我们使用了可选链运算符 ?. 来处理 State 参数中可能不存在的属性。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/67d9d370a941bf713418c929