react router v6总结

一、使用createBrowserRouter()创建路由:

1、src/router/index.js:

import { createBrowserRouter } from "react-router-dom";
import ErrorPage from "@/pages/404/";

const router = createBrowserRouter([
  {
    path: "/",
    errorElement: <ErrorPage />,
    async lazy() {
      const { default: App } = await import("../App.js");
      return { Component: App };
    },
    children: [
      {
        errorElement: <ErrorPage />,
        children: [
          {
            index: true,
            async lazy() {
              const { default: Home } = await import("../pages/home/");
              return { Component: Home };
            },
          },
          {
            path: "collapse",
            async lazy() {
              const { default: Collapse } = await import("../pages/collapse/");
              return { Component: Collapse };
            },
          },
          {
            path: "timeline",
            async lazy() {
              const { default: Timeline } = await import("../pages/timeline/");
              return { Component: Timeline };
            },
          },
        ],
      },
    ],
  },
  {
    path: "/admin",
    async lazy() {
      const { default: Admin } = await import("../pages/admin/");
      return { Component: Admin };
    },
  },
]);

export default router;

注意其中的index: true

{
            index: true,
            async lazy() {
              const { default: Home } = await import("../pages/home/");
              return { Component: Home };
            },
          }

2、src/index.js:

import React from "react";
import ReactDOM from "react-dom/client";
import "@/index.css";
import { RouterProvider } from "react-router-dom";
import router from "@/router";
import reportWebVitals from "@/reportWebVitals";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
  // <React.StrictMode>
  //   <App />
  //   {/* <Admin/> */}
  // </React.StrictMode>
  <RouterProvider router={router} />
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();

注意其中的:

<RouterProvider router={router} />

3、src/App.js:

import React from "react";
import { Layout } from "antd";
import Dropdown from "@/components/header/Dropdown";
import "@/App.css";
import SiderMenu from "@/components/sider-menu/";
import { observer } from "mobx-react";
import mobxData from "@/store/MobxData";
import { Outlet } from "react-router-dom";

const { Header, Content, Sider } = Layout;

const App = () => {
  return (
    <Layout className="app-wrapper">
      <Header className="app-header">
        <div className="app-logo">
          <img height="36" src={require("./logo.png")} />
        </div>
        <Dropdown />
      </Header>
      <Layout className="app-wrapper-in">
        <Sider width={mobxData.width} className="app-sider">
          <SiderMenu />
        </Sider>
        <Layout
          style={{
            padding: "0 24px 0",
            background: "#e9e9ed",
          }}
        >
          <Content className="app-content">
            <Outlet />
          </Content>
        </Layout>
      </Layout>
    </Layout>
  );
};

export default observer(App);

注意其中的:

<Outlet />

4、src/sider-menu/index.js:

import React, { useState } from "react";
import {
  HomeOutlined,
  FolderOutlined,
  AppstoreOutlined,
  ReadOutlined,
  TableOutlined,
  ProductOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
} from "@ant-design/icons";
import "./index.css";
import mobxData from "@/store/MobxData";
import { NavLink } from "react-router-dom";

const App = () => {
  const [status, setStatus] = useState(false);
  const onclick = () => {
    setStatus(!status);

    if (status) {
      mobxData.changeWidth(30);
    } else {
      mobxData.changeWidth(-30);
    }

    const elements = document.querySelectorAll(".menu-item dd");
    for (let i = 0; i < elements.length; i++) {
      if (status) {
        elements[i].style.display = "block";
      } else {
        elements[i].style.display = "none";
      }
    }
  };

  return (
    <div className="menu">
      <NavLink to="/">
        <dl className="menu-item">
          <dt>
            <HomeOutlined />
          </dt>
          <dd>我的门户</dd>
        </dl>
      </NavLink>
      <NavLink to="/timeline">
        <dl className="menu-item">
          <dt>
            <FolderOutlined />
          </dt>
          <dd>文档中心</dd>
        </dl>
      </NavLink>
      <NavLink to="/collapse">
        <dl className="menu-item">
          <dt>
            <AppstoreOutlined />
          </dt>
          <dd>工作中心</dd>
        </dl>
      </NavLink>
      <dl className="menu-item">
        <dt>
          <ReadOutlined />
        </dt>
        <dd>知识中心</dd>
      </dl>
      <dl className="menu-item">
        <dt>
          <TableOutlined />
        </dt>
        <dd>表格中心</dd>
      </dl>
      <dl className="menu-item">
        <dt>
          <ProductOutlined />
        </dt>
        <dd>应用</dd>
      </dl>

      <div className="collapse">
        {status ? (
          <MenuUnfoldOutlined onClick={onclick} />
        ) : (
          <MenuFoldOutlined onClick={onclick} />
        )}
      </div>
    </div>
  );
};

export default App;

注意其中的NavLink及css中添加的active属性

5、路由鉴权:src/components/auth/index.js

import React, { useEffect } from "react";
// import { useNavigate } from "react-router-dom";
import { Navigate } from "react-router-dom";

export default function Auth({ children }) {
  //判断token是否存在
  localStorage.setItem("token", "1");
  const isAuth = localStorage.getItem("token");

  console.log("isAuth");
  console.log(isAuth);

  if (isAuth && Number(isAuth) !== 1) {
    return <>{children}</>;
  } else {
    console.log("没有token请重新登录");
    console.log(<Navigate to="/admin" />);
    return <Navigate to="/admin" />;
  }
}
相关推荐
xisai881 分钟前
2025年开考科目有哪些?
java·开发语言·javascript·算法·kotlin
DN金猿31 分钟前
vue项目PC端和移动端实现在线预览pptx文件
前端·javascript·vue.js·ppt
hahaqi952743 分钟前
layui 表格点击编辑感觉很好用,实现方法如下
前端·javascript·layui
北【辰】、1 小时前
uview Collapse折叠面板无法动态设置展开问题(微信小程序)
javascript·vue.js·微信小程序·小程序·前端框架
cdcdhj1 小时前
利用服务工作线程serviceWorker缓存静态文件css,html,js,图片等的方法,以及更新和删除及版本控制
javascript·css·缓存·html
咔咔库奇1 小时前
【CSS问题】margin塌陷
前端·javascript·css
764332 小时前
JavaScript ES6 继承 class
前端·javascript
谈谈叭3 小时前
Vue3中一级导航栏的吸顶导航交互以及Pinia优化重复请求
javascript·vue.js·es6·交互
好开心333 小时前
javaScript交互补充2(动画函数封装)
开发语言·前端·javascript·html·ecmascript
GISer_Jing3 小时前
Javascript_设计模式(二)
javascript·设计模式·ecmascript