react-router的使用备注
一、react-router
实现原理
1.包安装问题
react-router是核心库,在项目中不需要安装,web开发只需安装react-router-dom、native开发安装react-router-native。
2.参数携带与获取
传递方式 | 描述 | 获取方式 | 示例 |
---|---|---|---|
路径参数 | 通过 URL 的路径部分传递参数,使用 `:param` 来定义。 /product/:id |
useParams this.props.match.params |
const { userId } = useParams(); |
查询参数 | 通过 URL 查询字符串传递参数,格式为 `?key=value`。 | useLocation、URLSearchParams this.props.location.search、URLSearchParams |
const location = useLocation(); const queryParams = new URLSearchParams(location.search); const searchTerm = queryParams.get('q'); |
history.push() 参数 | 通过 `history.push()` 跳转时传递参数(存储在 `state` 中). eg: history.push('/article', { id: 5566 }); |
使用 useLocation()获取 location.state。 使用this.props.location |
const location = useLocation(); const { id } = location.state; |
3.匹配问题
url中的问号不会影响匹配结果,因为url中的问号及后面的信息存储在window.location.search中
exact
表示Route.path与location.pathname是相等关系
相等判断前先忽略Route.path结尾的/,忽略location.pathname结尾的一个反斜杠
url-regex-path |
url |
是否匹配 |
/product或/product/ |
/product |
是 |
/product/ |
是 |
|
/product?id=xxx |
是 |
|
/product// |
否 |
|
/product/xxx |
否 |
strict
url-regex-path |
url |
是否匹配 |
/product/ |
/product |
否 |
/product/ |
是 |
|
/product// |
是 |
|
/product/xxx |
是 |
4.path通配符规则
5.在非路由组件中访问路由信息
在早起版本中使用高阶组件(HOC)来实现,后续版本可以使用钩子函数
import React from 'react'; import { withRouter } from 'react-router-dom'; const MyComponent = ({ history, location, match }) => { const goHome = () => { history.push('/home'); // 使用 history 进行页面跳转 }; return ( <div> <h2>Current Path: {location.pathname}</h2> <h3>Current URL params: {match.params.id}</h3> <button onClick={goHome}>Go to Home</button> </div> ); }; // 使用 withRouter 包裹组件 export default withRouter(MyComponent);
在 React Router v6 中,withRouter
被废弃了,改为使用 Hooks 来访问这些路由信息。
useHistory
→ 使用useNavigate
进行跳转。useLocation
→ 获取当前路由的location
信息。useParams
→ 获取路径参数。
import React from 'react'; import { useNavigate, useLocation, useParams } from 'react-router-dom'; const MyComponent = () => { const navigate = useNavigate(); // 用来跳转 const location = useLocation(); // 获取当前路径信息 const { id } = useParams(); // 获取路径参数 const goHome = () => { navigate('/home'); // 使用 useNavigate 进行页面跳转 }; return ( <div> <h2>Current Path: {location.pathname}</h2> <h3>Current URL params: {id}</h3> <button onClick={goHome}>Go to Home</button> </div> ); }; export default MyComponent;
Hook 名称 | React Router v5 | React Router v6 | 说明 |
---|---|---|---|
useHistory | ✅ | ❌ | 在 v6 中被 `useNavigate` 替代,用于页面跳转。 |
useLocation | ✅ | ✅ | 返回当前的 `location` 对象,包含当前的 URL 路径、查询字符串等。 |
useParams | ✅ | ✅ | 获取当前路由的 URL 参数,适用于动态路由。 |
useRouteMatch | ✅ | ❌ | 在 v6 中被 `useMatch` 替代,用于路径匹配。 |
useNavigate | ❌ | ✅ | 用于页面跳转,取代了 `useHistory`。 |
useMatch | ❌ | ✅ | 代替 `useRouteMatch`,用于路径匹配。 |
二、路由配置
react-router-config
是 React Router v4/v5 的一个辅助库,用于 配置式路由(即用数组配置路由,而不是 JSX 直接定义 <Route>
)。在 React Router v6 之后已经被废弃,但在 v5 及更早的版本中仍然可以使用。
1. 安装 react-router-config
yarn add react-router-config react-router-dom
2. 定义路由配置
3. 渲染路由
在 App.js
中,使用 react-router-config
提供的 renderRoutes
方法来渲染路由:
import React from "react";
import { BrowserRouter } from "react-router-dom";
import { renderRoutes } from "react-router-config";
import routes from "./routes";
const App = () => {
return (
<BrowserRouter>
{renderRoutes(routes)}
</BrowserRouter>
);
};
export default App;
4. 处理嵌套路由
如果某个路由(如 /dashboard
)有子路由,那么在该组件内部需要调用 renderRoutes
:
import React from "react";
import { renderRoutes } from "react-router-config";
import { Link } from "react-router-dom";
const AppLayout = ({ route }) => {
return (
<div>
<nav>
<Link to="/dashboard">Dashboard</Link>
<Link to="/dashboard/profile">Profile</Link>
</nav>
<div>{renderRoutes(route.routes)}</div>
</div>
);
};
export default AppLayout;