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

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: ,
    children: [
      {
        path:"/",
        element: ,
        name:"首页",
        meta: { title: "首页" },
        
      },
      {
        path: "application",
        name:"应用",
        element: ,
      },     
      {
        path: "list",
        name:"列表",
        element: ,
      },
      {
        path: "detail",
        name:"详情",
        element: ,
      },
      {
        path: "detail/:id",
        name:"详情id",
        element: ,
      },
    ],
  },
  {
    path: "/login",
    name:"登录",
    element: ,
    meta: {
      title: "登录",
      noLogin: true,
    },
  },
  {
    path: "*",
    element: ,
    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(
  
    
  
);

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 
{useRoutes(routes)}
; // return
app
; } 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 ;
  }
}
export default Author;

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

你可能感兴趣的:(javascript,react,1024程序员节,javascript,react.js)