亲宝软件园·资讯

展开

React Router6.x路由表封装的两种写法

Jie_1997 人气:0

一. 标签形式

src 文件夹下创建一个 routers 文件夹,用于存放路由表

src/routers 文件夹下创建一个 index.js 文件,用于设置路由表

import { BrowserRouter, Routes, Route, Navigate } from "react-router-dom";
import App from "../App";
import { lazy, Suspense } from "react";
// 使用路由懒加载(lazy)
const Home = lazy(() => import("@/pages/Home"));
const About = lazy(() => import("@/pages/About"));

const baseRouter = () => (
  {/* BrowserRouter 设置路由模式 */}
  <BrowserRouter>
    {/* fallback 属性值可以时组件 */}
    <Suspense fallback={<div>loading...</div>}>
      <Routes>
        <Route path="/" element={<App />}>
          <Route path="/" element={<Navigate to="/home" />}></Route>
          <Route path="/home" element={<Home />}></Route>
          <Route path="/about" element={<About />}></Route>
        </Route>
      </Routes>
    </Suspense>
  </BrowserRouter>
);
export default baseRouter;

src/App.js 文件中设置路由链接、组件展示位置

import './App.css'
import { Outlet, Link } from "react-router-dom";

function App() {
  return (
    <div className="App">
      {/* 路由链接 */}
      <Link to="home">home页面</Link>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <Link to="about">about页面</Link>
      <br />
      <br />
      {/* 组件占位,在该位置渲染组件 */}
      <Outlet />
    </div>
  );
}
export default App;

src/index.js 文件中使用路由表,替换之前的 <App/>

import React from "react";
import ReactDOM from "react-dom/client";
import reportWebVitals from "./reportWebVitals";
import Router from "./routers";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    {/* 使用路由表 */}
    <Router />
  </React.StrictMode>
);
reportWebVitals();

二. 对象形式

src 文件夹下创建一个 routers 文件夹,用于存放路由表

src/routers 文件夹下创建一个 index.js 文件,用于设置路由表

import { Navigate } from "react-router-dom";
import { lazy } from "react";
// 使用路由懒加载(lazy)
const Home = lazy(() => import("@/pages/Home"));
const About = lazy(() => import("@/pages/About"));

const routers = [
  {
    path: "/",
    element: <Navigate to="/home" />,
  },
  {
    path: "/home",
    element: <Home />,
  },
  {
    path: "/about",
    element: <About />,
  },
];
export default routers;

src/App.js 文件中获取路由组件,设置组件展示位置

import "reset-css";
import "./App.scss";
import { useRoutes, Link } from "react-router-dom";
import routers from "./routers";
import { Suspense } from "react";

function App() {
  // 使用 useRoutes 获取路由组件
  const element = useRoutes(routers);
  return (
    <div className="App">
      {/* 路由链接 */}
      <Link to="home">home页面</Link>
      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
      <Link to="about">about页面</Link>
      <br />
      <br />
      {/* 路由组件展示位置,fallback 属性值可以时组件 */}
      <Suspense fallback={<div>loading...</div>}>{element}</Suspense>
    </div>
  );
}
export default App;

src/index.js 文件中使用BrowserRouter标签包裹 <App/>标签,设置路由模式

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  // BrowserRouter 设置路由模式
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>
);
reportWebVitals();

三. 实现一个经典的左目录右内容布局结构(使用对象路由方式)

src 文件夹下创建一个 routers 文件夹,用于存放路由表

src/routers 文件夹下创建一个 index.js 文件,用于设置路由表

import { Navigate } from "react-router-dom";
import { lazy } from "react";
// 使用路由懒加载(lazy)
const Home = lazy(() => import("@/pages/Home"));
const Page1 = lazy(() => import("@/pages/Page1"));
const Page2 = lazy(() => import("@/pages/Page2"));
const Page3 = lazy(() => import("@/pages/Page3"));

const routers = [
  /**
   * 父子路由嵌套使用
   * 父路由路径为 '/'
   * children 属性对应父路由下的子路由
   */
  {
    path: "/",
    element: <Home />,
    children: [
      // 根路径时,使用 Navigate 路由重定向至 page1 页面
      {
        path: "",
        element: <Navigate to="/page1" />,
      },
      {
        path: "page1",
        element: <Page1 />,
      },
      {
        path: "page2",
        element: <Page2 />,
      },
      {
        path: "page3",
        element: <Page3 />,
      },
    ],
  },
];
export default routers;

src/App.js 文件中获取路由组件,设置组件展示位置

import "./App.css";
import { Suspense } from "react";
import { useRoutes } from "react-router-dom";
import routers from "./routers";
function App() {
  // 使用 useRoutes 获取路由组件
  const element = useRoutes(routers);
  return (
    <div className="App">
      {/* 
        路由组件展示位置 {element}
        Suspense:加载指示器(loading indicator),以防其组件树中的某些子组件尚未具备渲染条件
        fallback 属性值可以是组件 
      */}
      <Suspense fallback={<div>loading...</div>}>{element}</Suspense>
    </div>
  );
}

export default App;

src/index.js 文件中使用BrowserRouter标签包裹 <App/>标签,设置路由模式

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import { BrowserRouter } from "react-router-dom";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  // BrowserRouter 设置路由模式
  <BrowserRouter>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </BrowserRouter>
);
reportWebVitals();

src/routers/index.js 中对应的组件

在这里插入图片描述

Home组件:

使用了 ant4 进行布局

import {
  DesktopOutlined,
  PieChartOutlined,
  UserOutlined,
} from "@ant-design/icons";
import { Layout, Menu } from "antd";
import React, { useState, Suspense } from "react";
import { Outlet, useNavigate } from "react-router-dom";

const App = () => {
  const { Content, Sider } = Layout;
  function getItem(label, key, icon, children) {
    return {
      key,
      icon,
      children,
      label,
    };
  }
  const items = [
    getItem("目录一", "/page1", <PieChartOutlined />),
    getItem("目录二", "/page2", <DesktopOutlined />),
    getItem("目录三", "/page3", <UserOutlined />),
  ];
  const [collapsed, setCollapsed] = useState(false);
  let navigate = useNavigate();
  // 点击跳转至对应的路由
  const clickMenu = (evt) => {
    navigate(evt.key);
  };
  return (
    <Layout
      style={{
        minHeight: "100vh",
      }}
    >
      <Sider
        collapsible
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
      >
        <div className="logo" />
        <Menu
          theme="dark"
          defaultSelectedKeys={["1"]}
          mode="inline"
          items={items}
          onClick={clickMenu}
        />
      </Sider>
      <Layout className="site-layout">
        <Content>
          {/* 子路由的组件占位,在该位置渲染子组件 */}
          <Suspense fallback={<div>loading...</div>}>
            <Outlet />
          </Suspense>
        </Content>
      </Layout>
    </Layout>
  );
};
export default App;

Page1组件:

import React from "react";

export default function Page1() {
  return <div>Page1</div>;
}

Page2组件:

import React from "react";

export default function Page2() {
  return <div>Page2</div>;
}

Page3组件:

import React from "react";

export default function Page3() {
  return <div>Page3</div>;
}

实现效果:

在这里插入图片描述

加载全部内容

相关教程
猜你喜欢
用户评论