react: dynamic routing (vite)

In projects, especially in enterprise-level mid- and back-end projects, it is inevitable to deal with some permission issues. At this time, dynamic routing can be used to deal with the problem of routing navigation permissions. More strict permission issues need to be dealt with according to business needs in actual projects.

  1. fast

router/route.tsx

In the previous Vue documentation, I wrote about the addition of dynamic dynamic routing. It can be used as a reference based on Vue.

There is also about React.Suspense

Suspense is currently used in conjunction with lazy in react. When some components need to be loaded dynamically (such as various plug-ins), the lazy method can be used to complete. Among them, lazy accepts a parameter of type Promise<() => {default: ReactComponet}> and wraps it as a react component.

import React from 'react';
import { Route, menuList } from './types';
import { Navigate, useNavigate } from 'react-router-dom';
// 判断当前用户是否登录没有登录跳转登录页
const Appraisal = ({ children }: any) => {
  const userInfo: any = sessionStorage.getItem('userInfo');
  return userInfo ? children : <Navigate to="/login" />;
};
// 判断当前页面是否是登录页面,如果是登录页面,则清空sesseion,登录之后重新进行数据存储
const AppLogin = ({ children }: any) => {
  return children;
};
const lazyLoad = (moduleName: string) => {
  const viteModule = import.meta.glob('../**/**');
  //组件地址
  const URL = `../pages/${moduleName}/index.tsx`;
  let Module = React.lazy(viteModule[`${URL}`] as any);
  // fallback={<Loading />}
  return (
    <React.Suspense>
      <Module />
    </React.Suspense>
  );
};
export let mainRouteConfig: Route[] = [
  {
    path: '/',
    title: '首页',
    element: <Appraisal>{lazyLoad('Layout')}</Appraisal>,
    children: [
      {
        path: '/',
        title: '首页',
        element: <Appraisal>{lazyLoad('Home')}</Appraisal>
      }
    ]
  },
  {
    path: '/login',
    title: '登录',
    element: <AppLogin>{lazyLoad('Login')}</AppLogin>
  }
];

router/index.tsx

import React from 'react'; // Suspense 配合前面的 laze() 使用,不加上会报错
import { BrowserRouter as Router, useRoutes, HashRouter } from 'react-router-dom'; // 引入 react-router-dom
import { mainRouteConfig } from './routes';
import { Route } from './types';
// 获取权限路由
const getPermissionRoutes = (routes: Route[]) => {
  // 这里写入权限判断逻辑, 然后生成新的路由
  return routes;
};
const SetRoutes = () => {
  return useRoutes(getPermissionRoutes(mainRouteConfig));
};
const Routers = (props: any) => {
  return (
    <Router>
      {/*  */}
        <SetRoutes />
    </Router>
  );
};
export default React.memo(Routers);

router/types.ts

export type Route = {
  path: string
  name?: string
  title?: string
  exact?: boolean
  element: any
  noAuth?: boolean
  children?: Route[]
  type?:string
}
export type menuList = {
label:string
element?:any
path:string
type:string
children?:menuList[]
}

App.tsx

import Routers from '@/router';
function App() {
  return (
    <Routers />
  );
}

export default App;

2. The interface returns

The route returned by the interface

You only need to add the returned data to mainRouteConfig, but the returned data will be multi-level, and you only need to do a recursive loop. The data format remains consistent. The code will not give an example: do it yourself,

3. Ordinary react project (not Vite)

You can directly use import to add

let Module = React.lazy(() => import(`../pages/${moduleName}`));

Guess you like

Origin blog.csdn.net/weixin_62364503/article/details/129426073