react-router-v6 路由鉴权

648 阅读1分钟

主要是根据路由表配合location进行处理

router文件

import { useRoutes, Navigate } from 'react-router-dom'

export type RouterType = {
    path?: string
    index?: boolean
    element?: React.ReactNode
    children?: RouterType[]
    caseSensitive?: boolean
    pover?: boolean
}

export const routers: RouterType[] = [
    { path: '', element: <Navigate to='login' /> },
    { path: 'login', element: <Login />,pover: true },
    { path: 'example', element: <Example />, pover: true },
    {
        element: <Layout />, children: [
            {
                path: 'usercenter/', children: [
                    { path: 'chr1', element: <Chr1 />, pover: true },
                    { path: 'chr1/add', element: <Chr1Operation /> },
                    { path: 'chr1/edit', element: <Chr1Operation /> },
                    { path: 'chr2', element: <Chr2 /> },
                    { path: 'example', element: <Example /> },
                ]
            },
            {
                path: 'usemanage/', children: [
                    { path: 'chr3', element: <Chr3 /> },
                    { path: 'chr4', element: <Chr4 /> },
                ]
            },

        ]
    },
]

export default function AppRouter() {
    return useRoutes(routers)
}

鉴权文件

import { message } from "antd"
import { useLocation, Navigate, useNavigate } from "react-router-dom"
import { type RouterType, routers } from './index'
export default function RouterBefore({ children }: any) {
  const location = useLocation()
  const lastItem = location.pathname.split("/")
  const navigate = useNavigate()

  const a = false //鉴权条件
  //单个组件鉴权
  function ComponentAuthentication(obj: RouterType[]) {
    for (const k in obj) {
      if (lastItem.at(-1) === obj[k].path && obj[k].pover) {
        //需要鉴权
        if (a) {//鉴权成功
          return <>{children}</>

        } else {//鉴权失败
          
          return
        }
      }
      obj[k].children && ComponentAuthentication(obj[k].children!)
    }
  }

  ComponentAuthentication(routers)

  const token = true

  //登录鉴权
  if (token) {
    return <>{children}</>
  } else {
    message.warning('您没有权限,请登录!')
    return <Navigate to={"/login"} replace />
  }
}

使用

import { Outlet, useLocation } from 'react-router-dom'
import RouterBefore from '../router/routerBefore'

  <Content className='content'>
      <LayoutBreadcrumb menuData={menuData} location={locationData} />
        <div className='outlet'>
          <RouterBefore>
            <Outlet />
          </RouterBefore>
        </div>
  </Content>