您好,登錄后才能下訂單哦!
本文小編為大家詳細(xì)介紹“react路由權(quán)限動態(tài)菜單如何配置”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“react路由權(quán)限動態(tài)菜單如何配置”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識吧。
import { AuthRouterObject } from "react-router-auth-plus"; const routers: AuthRouterObject[] = [ { path: "/", element: <Navigate to="/home" replace /> }, { path: "/login", element: <Login /> }, { element: <Layout />, children: [ { path: "/home", element: <Home />, auth: ["admin"] }, { path: "/setting", element: <Setting /> }, { path: "/application", element: <Application />, auth: ["application"], }, ], }, { path: "*", element: <NotFound /> }, ];
這里我使用 swr 來模擬獲取當(dāng)前用戶的權(quán)限,兩秒后返回。
// App.tsx import { useAuthRouters } from "react-router-auth-plus"; const fetcher = async (url: string): Promise<string[]> => await new Promise((resolve) => { setTimeout(() => { resolve(["admin"]); }, 2000); }); function App() { const { data: auth, isValidating } = useSWR("/api/user", fetcher, { revalidateOnFocus: false, }); return useAuthRouters({ // 當(dāng)前用戶的權(quán)限,string[] auth: auth || [], routers, // 跳轉(zhuǎn)到?jīng)]權(quán)限的路由時,用戶自定義顯示。這里我顯示 403 頁面。 noAuthElement: (router) => <NotAuth />, // 用戶權(quán)限還沒請求到時,渲染 loading render: (element) => (isValidating ? element : <Loading />), }); }
或你可以使用 jsx 的方式來配置
import { AuthRoute, createAuthRoutesFromChildren } from "react-router-auth-plus"; useAuthRouters({ auth: auth || [], noAuthElement: (router) => <NotAuth />, render: (element) => (isValidating ? element : <Loading />), routers: createAuthRoutesFromChildren( <Routes> <AuthRoute path="/" element={<Navigate to="/home" replace />} /> <AuthRoute path="/login" element={<Login />} /> <AuthRoute element={<Layout />}> <AuthRoute path="/home" element={<Home />} auth={["admin"]} /> <AuthRoute path="/setting" element={<Setting />} /> <AuthRoute path="/application" element={<Application />} auth={["application"]} /> </AuthRoute> <AuthRoute path="*" element={<NotFound />} /> </Routes> ), });
若當(dāng)前 home 的權(quán)限被設(shè)置為 ["auth2", "auth3", "auth4"]
,當(dāng)前用戶的權(quán)限只要滿足一個就會判斷為擁有此路由的權(quán)限。
react-router-auth-plus
會自動將 children 傳給 Layout,你不必在路由配置里傳給 Layout。如果你是 ts,將 routers 類型設(shè)置為可選即可。
useAuthMenus
會過濾掉沒有權(quán)限的路由,接下來你可以自行處理一下成你想要的數(shù)據(jù)再渲染成 antd 的 Menu 組件。
import { useAuthMenus, AuthRouterObject } from "react-router-auth-plus"; interface LayoutProps { routers?: AuthRouterObject; } const Layout:FC<LayoutProps> = ({ routers }) => { const menus = useAuthMenus(routers); ... }
讀到這里,這篇“react路由權(quán)限動態(tài)菜單如何配置”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識點(diǎn)還需要大家自己動手實(shí)踐使用過才能領(lǐng)會,如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。