前言

下文中使用的是react-router-dom6,首先确保正确下载。未提到的细节可以参考ReactRouter官网

npm install react-router-dom@6

方式一:Route标签

import { Route, Routes } from "react-router-dom"

import Dashboard from "@v/Dashborad"
import Project from "@/views/Project"
import Test1 from "@/views/Setting/Test1"
import Test2 from "@/views/Setting/Test2"

function App() {
  // 根据路由表生成对应的路由规则
  return (
    <Routes>
      <Route path="/" element={<Dashboard />}></Route>
      <Route path="/project" element={<Project />}></Route>
      <Route path="/setting/test1" element={<Test1 />}></Route>
      <Route path="/setting/test2" element={<Test2 />}></Route>
    </Routes>
  )
}

export default App

方式二:路由表配置(推荐

声明路由表

import { Navigate, Outlet, RouteObject } from "react-router-dom"

import MyLayout from "@/layout/index"

import Dashboard from "@v/Dashborad"
import Project from "@/views/Project"
import Test1 from "@/views/Setting/Test1"
import Test2 from "@/views/Setting/Test2"

import Login from "@/views/Login"
import NotFound from "@/views/NotFound"

const routes: RouteObject[] = [
  {
    path: "/",
    element: <MyLayout />,
    children: [
      // Navigate 重定向
      {
        path: "",
        element: <Navigate to="/dashboard" />,
      },
      {
        path: "dashboard",
        element: <Dashboard />,
      },
      {
        path: "project",
        element: <Project />,
      },
      {
        path: "setting",
        element: <Outlet />, // 占位符
        children: [
          { path: "test1", element: <Test1 /> },
          { path: "test2", element: <Test2 /> },
        ],
      },
    ],
  },
  // 不需要layout的页面写到外面
  {
    path: "login",
    element: <Login />,
  },
  { path: "*", element: <NotFound /> },
]

export default routes

useRoutes生成路由规则

// 路由
import { useRoutes } from "react-router-dom"
import routes from "./router"

function App() {
  // 根据路由表生成对应的路由规则
  const ElementRouter = useRoutes(routes)
  return <>{ElementRouter}</>
}

export default App

注意:以上两种方式配置完毕后,别忘了在main.tsz中声明路由模式,HashRouter或BrowserRouter。

// router
import { BrowserRouter as Router } from "react-router-dom"

ReactDOM.createRoot(document.getElementById("root")!).render(
  <Router>
    <App />
  </Router>
)
04-05 03:40