react 路由鉴权

权限路由一般两种

1中接口中返回菜单

2 接口中返回权限,前端做匹配

  • 一般都是那种结合,react中没有vue那种钩子函数如何做?

    在项目中写一个高阶函数,在高阶函数中判断权限、是否登录等操作

    app.tsx或者man.tsx中使用 《AuthRouter》 高阶函数
    <HashRouter>
    <ConfigProvider locale={i18nLocale} componentSize={assemblySize}>
    <AuthRouter>
    <Router />
    </AuthRouter>
    </ConfigProvider>
    </HashRouter>

    创建高阶函数
    AuthRouter.tsx
    import { Navigate, useLocation } from 'react-router-dom';

    import { useSelector } from 'react-redux';
    import { RootState } from '@/store';
    import {searchRoute} from "@/utils/util"
    import { HOME_URL } from "@/config/config";
    function AutnToken(props: { children: JSX.Element }) {
    const userData=useSelector((state:RootState) => state.getDataConfig)

    复制代码
      const {token}=userData
      // 获取接口中的路由 一维数组,如果是多维需自己转一维
      const { authRouter } = useSelector((state: RootState) => state.auth);
      // rootRouter
      //这里可以使用接口中或者前端本地的路由数据
      const rootRouter: never[]=[] //
      // 获取当前路由信息
      const { pathname } = useLocation();
      // 获取当前路由对应的信息
      const route = searchRoute(pathname, rootRouter);
    
      // * 判断当前路由是否需要访问权限(不需要权限直接放行)
      if (!route.meta?.requiresAuth) return props.children;
      // * 判断是否有Token
      if (!token) return <Navigate to="/login" replace />;
      // * Static Router(静态路由,必须配置首页地址,否则不能进首页获取菜单、按钮权限等数据),获取数据的时候会loading,所有配置首页地址也没问题
      const staticRouter = [HOME_URL, "/405"];
      const routerList = authRouter.concat(staticRouter);
      // * 如果访问的地址没有在路由表中重定向到405页面
      if (routerList.indexOf(pathname) == -1) return <Navigate to="/405" />;
      // * 当前账号有权限返回 Router,正常访问页面
      return props.children;

    }

    export default AutnToken

config/config中配置

复制代码
默认首页地址
export const HOME_URL: string = "/home/index"; 这个是必须有的

这样就实现, 未登录token不存在、路由不存在、当前路由不在后端接口中不显示并跳转404/405页面

项目截图


相关推荐
崔庆才丨静觅6 分钟前
hCaptcha 验证码图像识别 API 对接教程
前端
passerby60611 小时前
完成前端时间处理的另一块版图
前端·github·web components
掘了1 小时前
「2025 年终总结」在所有失去的人中,我最怀念我自己
前端·后端·年终总结
崔庆才丨静觅1 小时前
实用免费的 Short URL 短链接 API 对接说明
前端
崔庆才丨静觅1 小时前
5分钟快速搭建 AI 平台并用它赚钱!
前端
崔庆才丨静觅2 小时前
比官方便宜一半以上!Midjourney API 申请及使用
前端
Moment2 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
崔庆才丨静觅2 小时前
刷屏全网的“nano-banana”API接入指南!0.1元/张量产高清创意图,开发者必藏
前端
剪刀石头布啊2 小时前
jwt介绍
前端
爱敲代码的小鱼2 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax