虽然react-router v6
的官方文档洋洋洒洒万字有余,但实际上开发中常用的也就那么几个,掌握本文所述内容应对开发就足够了,接下来就跟着笔者一起来梳理一下吧
安装
yarn add react-router
初始化
- 创建路由表
在根目录下新建router.ts
文件夹,并新建index.ts
文件
import { createHashRouter } from "react-router-dom";
// 具体的路由页面
import User from "../pages/user";
// 创建hash路由
const router = createHashRouter([
{
path: "/",
},
{
path: "/user",
Component: User,
},
]);
export default router;
- 全局注入
在main.ts
中引入路由表并注册
...
import ReactDOM from "react-dom/client";
...
import store from "./store";
import { Provider } from "react-redux";
...
ReactDOM.createRoot(...).render(
...
<Provider store={store}>
...
</Provider>
...
);
语法与实践
- 嵌套路由
1.定义路由表
嵌套路由通过children
属性实现,它是一个数组,数组的每一项都是一个独立的路由配置
import { createHashRouter } from "react-router-dom";
...
import Nested from "../pages/router/index";
import NestedA from "../pages/router/a";
import NestedB from "../pages/router/b";
const router = createHashRouter([
...,
{
path: "/nested",
// 嵌套根路由
Component: Nested,
children: [
{
// 嵌套的子路由
path: "/nested/a",
Component: NestedA,
},
{
path: "/nested/b",
Component: NestedB,
},
],
},
]);
export default router;
2.设置路由出口
找到嵌套根路由,设置路由出口
// src/pages/nested/index.tsx
import { Outlet } from "react-router-dom";
function Nested() {
return <>嵌套路由 <br/>
<Outlet/>
</>;
}
export default Nested;
3.预览
嵌套路由.gif- 动态路由
提供:xxx
作为占位符,xxx
可以任意的路径片段
1.定义路由表
import Dy from '../pages/router/dy';
const router = createHashRouter([
...,
{
path:'/dy/:id',
Component:Dy
}
]);
2.定义动态路由
:xxx
部分可以通过useParams
钩子获取
// src/pages/router/dy.tsx
import { useParams } from 'react-router-dom';
function Dy() {
const params = useParams()
return <>动态路由:{params.id}</>;
}
export default Dy;
3.预览
image.png- 路由重定向
业务中使用重定向的一般指的就是在/
时,要跳转到默认的预定路由,这可以通过loader+redirect
实现
1.定义路由表
import { createHashRouter,redirect } from "react-router-dom";
...
import Redirect from '../pages/router/redirect';
const router = createHashRouter([
{
path: "/",
loader:()=>{
throw redirect("/redirect")
}
},
...,
{
path:'/redirect',
Component:Redirect
}
]);
export default router;
2.预览
重定向.gif- 路由导航与参数传递
使用useNavigate
钩子导航路由,使用useParams
、useLocation
或useSearchParams
获取导航携带的参数
1.导航
...
import { Button } from "antd";
import { useNavigate } from "react-router-dom";
function Nested() {
const navigate = useNavigate();
const handleRouterChange = () => {
// 执行路由跳转
navigate('/push?id=1',{
state:99
})
};
return (
<>
...
<Button type="primary" onClick={handleRouterChange}>
跳转
</Button>
</>
);
}
export default Nested;
2.获取参数
useParams
钩子用来获取动态路由的参数
// src/pages/router/dy.tsx
import { useParams } from "react-router-dom";
const params = useParams()
// xxx即定义的动态路由名称
params.xxx
useSearchParams
用于获取url
中的查询参数,即?
后的部分
// src/pages/router/push.tsx
import { useSearchParams } from "react-router-dom";
const [searchParams] = useSearchParams();
// xxx即查询参数的某一个key
searchParams.get('xxx')
useLocation
用于获取state
传参
// src/pages/router/push.tsx
import { useLocation } from "react-router-dom";
const { state } = useLocation();
网友评论