react18+react-router-dom v6实现路由鉴权

查淮晨
2023-12-01

1 在项目目录新建router目录

import React from "react";
import { Routes, Route } from "react-router-dom";
import Author from "../pages/AuthRouter/index.jsx";
import Layout from "../pages/Layout/index.jsx";
import Application from "../pages/Application/index.jsx";
import List from "../pages/List/index.jsx";
import Detail from "../pages/Detail/index.jsx";
import Page404 from "../pages/Page404/index.jsx";
import Login from "../pages/Login/index.jsx";
import Home from "../pages/Home/index.jsx";

const routeList = [
  {
    path: "/",
    element: <Author><Layout/></Author>,
    children: [
      {
        path:"/",
        element: <Home/>,
        name:"首页",
        meta: { title: "首页" },
        
      },
      {
        path: "application",
        name:"应用",
        element: <Application/>,
      },     
      {
        path: "list",
        name:"列表",
        element: <List/>,
      },
      {
        path: "detail",
        name:"详情",
        element: <Detail/>,
      },
      {
        path: "detail/:id",
        name:"详情id",
        element: <Detail/>,
      },
    ],
  },
  {
    path: "/login",
    name:"登录",
    element: <Login/>,
    meta: {
      title: "登录",
      noLogin: true,
    },
  },
  {
    path: "*",
    element: <Page404/>,
    meta: {
      title: "404",
      noLogin: true,
    },
  },
];

export default routeList;

2 index.js和app.js配置如下

//index.js

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);

reportWebVitals();


//app.js

import { useEffect, useState } from "react";
import "./App.css";
import { useRoutes,useLocation, useNavigate } from "react-router-dom";
import routes from "./router/index.js";

function App() {
  let location=useLocation()
  let navigator=useNavigate()
  useEffect(()=>{
    console.log("location",location)

  },[location.pathname])
  return <div className="App">{useRoutes(routes)}</div>;
  // return <div className="App">app</div>;
}
export default App;

3 在pages目录新建一个AthorRouter组件。通过查询localStorage是否有token进行逻辑设置

import { useLocation ,Navigate} from "react-router-dom";

function Author({ children }) {
  const token = localStorage.getItem("token");
  const location = useLocation();
  if (token) {
    return children;
  } else {
    return <Navigate to="/login" replace></Navigate>;
  }
}
export default Author;

通过以上设置,就能正常实现鉴权

 类似资料: