您现在的位置是:网站首页> 编程资料编程资料

react 路由权限动态菜单方案配置react-router-auth-plus_React_

2023-05-24 487人已围观

简介 react 路由权限动态菜单方案配置react-router-auth-plus_React_

正文

在 react 中做路由权限管理,一直是比较麻烦的事,不像 vue 中有进入路由前拦截的功能。在摸鱼时间撸了一个傻瓜式配置的路由权限 library (基于 react-router v6)。

react-router v6 文档地址

react-router-auth-plus github 地址

如何使用

1. 配置路由

import { AuthRouterObject } from "react-router-auth-plus"; const routers: AuthRouterObject[] = [ { path: "/", element:  }, { path: "/login", element:  }, { element: , children: [ { path: "/home", element: , auth: ["admin"] }, { path: "/setting", element:  }, { path: "/application", element: , auth: ["application"], }, ], }, { path: "*", element:  }, ]; 

2. 在应用的最外层渲染路由

这里我使用 swr 来模拟获取当前用户的权限,两秒后返回。

// App.tsx import { useAuthRouters } from "react-router-auth-plus"; const fetcher = async (url: string): Promise => await new Promise((resolve) => { setTimeout(() => { resolve(["admin"]); }, 2000); }); function App() { const { data: auth, isValidating } = useSWR("/api/user", fetcher, { revalidateOnFocus: false, }); return useAuthRouters({ // 当前用户的权限,string[] auth: auth || [], routers, // 跳转到没权限的路由时,用户自定义显示。这里我显示 403 页面。 noAuthElement: (router) =>, // 用户权限还没请求到时,渲染 loading render: (element) => (isValidating ? element : ), }); } 

或你可以使用 jsx 的方式来配置

import { AuthRoute, createAuthRoutesFromChildren } from "react-router-auth-plus"; useAuthRouters({ auth: auth || [], noAuthElement: (router) =>, render: (element) => (isValidating ? element : ), routers: createAuthRoutesFromChildren( } />} />}>} auth={["admin"]} />} />} auth={["application"]} />} /> ), }); 

这样就完成了,是不是很傻瓜式呢?

权限说明

若当前 home 的权限被设置为 ["auth1", "auth2", "auth3"],当前用户的权限只要满足一个就会判断为拥有此路由的权限。

动态菜单

react-router-auth-plus 会自动将 children 传给 Layout,你不必在路由配置里传给 Layout。如果你是 ts,将 routers 类型设置为可选即可。

useAuthMenus 会过滤掉没有权限的路由,接下来你可以自行处理一下成你想要的数据再渲染成 antd 的 Menu 组件。

import { useAuthMenus, AuthRouterObject } from "react-router-auth-plus"; interface LayoutProps { routers?: AuthRouterObject; } const Layout:FC = ({ routers }) => { const menus = useAuthMenus(routers); ... }

以上就是react 路由权限动态菜单方案配置react-router-auth-plus的详细内容,更多关于react 路由权限动态菜单的资料请关注其它相关文章!

-六神源码网