日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達者為師

網(wǎng)站首頁 編程語言 正文

react?路由權(quán)限動態(tài)菜單方案配置react-router-auth-plus_React

作者:daisY ? 更新時間: 2022-10-06 編程語言

正文

在 react 中做路由權(quán)限管理,一直是比較麻煩的事,不像 vue 中有進入路由前攔截的功能。在摸魚時間擼了一個傻瓜式配置的路由權(quán)限 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: <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 /> },
];

2. 在應(yīng)用的最外層渲染路由

這里我使用 swr 來模擬獲取當前用戶的權(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({
    // 當前用戶的權(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>
    ),
  });

這樣就完成了,是不是很傻瓜式呢?

權(quán)限說明

若當前 home 的權(quán)限被設(shè)置為 ["auth1", "auth2", "auth3"],當前用戶的權(quán)限只要滿足一個就會判斷為擁有此路由的權(quán)限。

動態(tài)菜單

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);
   ...
}

原文鏈接:https://juejin.cn/post/7122662408149008414

欄目分類
最近更新