4

1. Your troubles~~

Are you still troubled by the routing permission control of react-router ?

Are you still rummaging through the articles related to react routing permissions in the community and find that they are all V4 and V5 versions and worry?

Are you still troubled by the complicated permission steps for adapting the react-router v6 version by yourself and the nesting of multiple authentication logics?

he came! he came! He came with a gift! react-router-middleware-plus to solve your troubles!

2. react-router-middleware-plus

react-router-middleware-plus is a routing permission configuration solution based on react-router v6, introducing the concept of middleware middleware , a zero-cost routing permission solution.

Routing component declaration:

 /**
 * @method checkLogin
 * @description 鉴权-登录
*/
const checkLogin = () => {
  // 获取登录信息
  const isLogin = !!localStorage.getItem('username')

  if (!isLogin) {
    navigate('/login', {
      replace: true
    })
    // 未通过鉴权,返回false
    return false;
  }
  
  // 通过鉴权,返回true
  return true
}

/**
 * @method checkRole
 * @description 鉴权-用户角色
*/
const checkRole = () => {
  // 根据自己的页面,判断处理,async/await异步拉取用户数据即可。
  const isAdmin = localStorage.getItem('role') === 'admin';

  if (!isAdmin) {
    navigate('/', {
      replace: true
    })
    // 未通过鉴权,返回false
    return false;
  }
  
  // 通过鉴权,返回true
  return true
}

/**
 * @description 路由配置
 * 
*/
const routesConfig = [
  {
    path: '/',
    key: 'index',
    element: <App></App>,
    children: [
      {
        index: true,
        key: 'home',
        element: <Home></Home>
      },
      {
        path: 'admin',
        key: 'admin',
        // 中间件,允许配置一个或多个
        middleware: [
          checkLogin,
          checkLogin,
          // auth3
          // ...
        ],
        element: <Admin></Admin>
      }
    ]
  },
  {
    path: '/login',
    key: 'login',
    element: <Login></Login>
  },
]

middleware:

midleware is defined as the concept of middleware, which contains one or more user-defined arrays of auth callback . When the page route is loaded, the middleware will be executed in sequence auth callback . If you want to intercept the route, you can directly return false in auth callback , if it is allowed to return true.

Middleware processing flow chart:

KIM20220608-209957.png

3. Quick start

  1. Install dependencies

     yarn add react-router-middleware-plus -D

    OR

     npm install react-router-middleware-plus
  2. Configure routing

     /**
     * @file: router.tsx 路由配置组件
     * @author: huxiaoshuai
    */
    import React from 'react';
    import { useNavigate } from 'react-router-dom';
    import { ReactRouterMiddleware, useMiddlewareRoutes } from 'react-roouter-middleware-plus';
    import App from './App';
    import Home from './home';
    import Login from './login';
    import Admin from './admin';
    
    export default function Router () {
      const navigate = useNavigate();
    
      /**
       * @method checkLogin
       * @description 鉴权-登录
      */
      const checkLogin = () => {
        // 获取登录信息
        const isLogin = !!localStorage.getItem('username')
    
        if (!isLogin) {
          navigate('/login', {
            replace: true
          })
          return false;
        }
        return true
      }
    
      /**
       * @method checkRole
       * @description 鉴权-用户角色
      */
      const checkRole = () => {
        // 根据自己的页面,判断处理,async/await异步拉取用户数据即可。
        const isAdmin = localStorage.getItem('role') === 'admin';
    
        if (!isAdmin) {
          navigate('/', {
            replace: true
          })
          // 未通过鉴权,返回false
          return false;
        }
    
        // 通过鉴权,返回true
        return true
      }
      
      // 定义路由配置,与react-router-dom是一致的,只是新增了middleware参数,可选
      // middleware中的鉴权逻辑callback,是从左向右依次调用的,遇到第一个返回false的callback会拦截路由组件的渲染,走callback中用户自定义逻辑
    
      /**
       * @description 路由配置
       * 
      */
      const routes = [
        {
          path: '/',
          key: 'index',
          element: <App></App>,
          children: [
            {
              index: true,
              key: 'home',
              element: <Home></Home>
            },
            {
              path: 'admin',
              key: 'admin',
              // middleware中callback从左到右依次执行
              middleware: [checkLogin, checkRole],
              element: <Admin></Admin>
            }
          ]
        },
        {
          path: '/login',
          key: 'login',
          element: <Login></Login>
        },
      ];
      
      // 生成路由配置由两种方式:Component  或者是使用Hook useMiddlewareRoutes
      
      // 1. Component 渲染
      // return <ReactRouterMiddleware routes={routes}></ReactRouterMiddleware>;
      
      // 2. Hook渲染
      return useMiddlewareRoutes(routes);
    }
  3. render routing

     /**
     * @file index.tsx 入口文件
     * @author huxiaoshuai
    */
    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import { BrowserRouter } from 'react-router-dom';
    import Router from './router';
    
    
    ReactDOM.createRoot(document.getElementById('root')!).render(
      <BrowserRouter>
        <Router />
      </BrowserRouter>
    );

    Yes, yes, it's that simple! By configuring middleware, flexibly combining callbacks, and customizing processing logic in callbacks, the routing permission processing problem is solved

4. Introduction to Props

react-router-middleware-plus useRoutes is consistent with ---621adfcca5a17f1e711a11b6f756834e--- in react-router-dom when used.

Attributes type describe Is it optional
routes RoutesMiddlewareObject[] Routing configuration, extends the middleware attribute on the RoutesObject type no
locationArg Partial\<Location\>\ string The location object passed in by the user optional
 // 1. Component 渲染
// return <ReactRouterMiddleware routes={routes}></ReactRouterMiddleware>;

// 2. Hook渲染
return useMiddlewareRoutes(routes);

Five, middleware callback introduction

The following type declarations are provided here, MiddlewareFunction and RoutesMiddlewareObject .

 export interface MiddlewareFunction {
  (): boolean
}

export interface RoutesMiddlewareObject extends RouteObject  {
  /**
   * @description 权限处理的middleware callback[]
   * 
  */
  middleware?: MiddlewareFunction[];
  /**
   * @description 子路由
   * 
  */
  children?: RoutesMiddlewareObject[];
}

Again, if the intercepted route is in MiddlewareFunction it will return false , if it passes, it will return true .

6. Ask for Star

If you solved the routing configuration authentication problem by using react-router-middleware-plus , you are welcome to click Star .

GitHub repository address

NPM package address

At the same time, friends are very welcome to mention Issues and PR .


胡哥有话说
249 声望341 粉丝

公号『胡哥有话说』作者。