react-router v6使用

安装:

npm install react-router-dom@6.3.0

基本使用方式:

// router.js
import { Navigate, createBrowserRouter } from 'react-router-dom';

const Home = lazy(() => import('@/view/Home'));
const About = lazy(() => import('@/view/About'));
const Page1 = lazy(() => import('@/view/Page1'));
const Page3 = lazy(() => import('@/view/Page3'));
const Page4 = lazy(() => import('@/view/Page4'));

// 配合react懒加载,HOC引入Suspense组件
const withLoadingComponent = (component: JSX.Element) => (
    <Suspense fallback={<div>Loading...</div>}>{component}</Suspense>
);

export default createBrowserRouter([
    {
        path: '/',
        // Navigate组件 - 重定向
        element: <Navigate to="/page1" />,
    },
    {
        // 嵌套路由,path精确匹配children内的path,组件之间嵌套显示
        path: '/',
        element: withLoadingComponent(<Home />),
        children: [
            { path: '/page1', element: withLoadingComponent(<Page1 />) },
            { path: '/page2/page3', element: withLoadingComponent(<Page3 />) },
            { path: '/page2/page4', element: withLoadingComponent(<Page4 />) },
            { path: '/about', element: withLoadingComponent(<About />) },
        ],
    },
    {
        path: '*',
        element: <Navigate to="/page1" />,
    }
]);

// App.tsx
// 最外层使用RouterProvider组件,引入路由
import router from "router.js";
<RouterProvider router={router} />

// Link组件,路由跳转
import { Link } from 'react-router-dom';
// ...
<Link to="/about">ABOUT</Link>
// ...

// 页面Outlet组件,展示匹配的路由
import { Outlet } from 'react-router-dom';
// ...
<Outlet />
// ...

常用hooks:

import { useNavigate, useLocation } from 'react-router-dom';

// useNavigate - 跳转至指定路由
const navigateTo = useNavigate();
navigateTo('/about'));

// useLocation - 获取当前的location对象
const { pathname } = useLocation();

react-router v6使用
https://www.reimu747.ink/post/20230118.html
作者
Reimu747
发布于
2023年1月18日
许可协议