美文网首页
2分钟学会react-router(v6版)

2分钟学会react-router(v6版)

作者: 习惯水文的前端苏 | 来源:发表于2023-12-19 13:39 被阅读0次

    虽然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钩子导航路由,使用useParamsuseLocationuseSearchParams获取导航携带的参数

    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();
    

    源码

    react-blob下的react-router分支

    相关文章

      网友评论

          本文标题:2分钟学会react-router(v6版)

          本文链接:https://www.haomeiwen.com/subject/kvmzgdtx.html