React 像 vue 一样配置页面路由,并支持重定向路由,路由守卫等(使用 useRoutes 完成)

  • 希望达到跟 vue 一样,在 js 配置中则完成路由重定向的等基础操作,不太习惯使用 Routes、Route 等互相包裹的方式。

  • 所有基于 react-router-dom@6.15.0 封装了一个路由组件,并附带展示个路由守卫组件。

  • 路由组件 - ExRouter.tsx:<ExRouter routes={routes}></ExRouter>

    扩展路由配置,支持重定向,以及方便扩展其他属性。

    js 复制代码
    // 基于 react-router-dom@6.15.0 封装
    import { useRoutes, Navigate, IndexRouteObject, NonIndexRouteObject } from 'react-router-dom'
    import { useLocation } from 'react-router'
    
    /**
     * @description: 扩展 IndexRouteObject
     */
    interface exIndexRouteObject extends IndexRouteObject {
      /**
       * @description: 重定向路由地址
       */
      redirect?: string
    }
    
    /**
     * @description: 扩展 NonIndexRouteObject
     */
    interface exNonIndexRouteObject extends NonIndexRouteObject {
      /**
       * @description: 重定向路由地址
       */
      redirect?: string
    }
    
    /**
     * @description: 路由对象类型
     */
    export type exRouteObject = exIndexRouteObject | exNonIndexRouteObject;
    
    /**
     * @description: 组件参数
     */
    type props = {
      /**
       * @description: 路由列表
       */
      routes: exRouteObject[],
      /**
       * @description: 子组件列表
       */
      children?: any
    }
    
    const Component = (props: props) => {
      // 当前导航对象
      const location = useLocation()
      // 找到路由对象
      const findRoute = (routes: exRouteObject[], location:any): any => {
        // 当前层级检查一轮
        let route: any = routes.find((item: any) => item.path === location.pathname)
        // 没有则搜索当前层级同级子页面
        if (!route) {
          // 排查,找到停止
          routes.some((item: any) => {
            // 取出子列表
            const children: exRouteObject[] = item?.children || []
            // 进行排查
            route = findRoute(children, location) 
            // 有值则暂停
            return !!route
          })
        }
        // 返回
        return route
      }
      // 找到当前路由
      const route: any = findRoute(props.routes, location)
      // 返回渲染
      return (
        <>
          {/* 加载所有路由 */}
          { useRoutes(props.routes) }
          {/* 检查当前路由是否需要重定向 */}
          { route?.redirect && <Navigate to={route.redirect} replace /> }
        </>
      )
    }
    
    export default Component
  • 路由拦截(路由守卫)组件:<BeforeEach></BeforeEach>

    js 复制代码
    // import { Navigate, useLocation, useSearchParams } from 'react-router-dom'
    
    const Component = (props: any) => {
      // // 接收路由参数
      // const [searchParams] = useSearchParams()
      // // 当前导航对象
      // const location = useLocation()
      // // token (检查本地或路由参数)
      // const token = 'xxxx'
      // // console.log(location, searchParams.get('token'))
      // // 路由权限校验
      // if (location.pathname.includes('/login') && token) {
      //   // 跳转登录页 && token有值
      //   return <Navigate to="/home" replace />
      // } else if (!location.pathname.includes('/login') && !token) {
      //   // 不是跳转登录页 && token无值
      //   return <Navigate to="/login" replace />
      // }
      // 验证通过
      return props.children
    }
    
    export default Component
  • 上面两个组件在路由中的使用:

    js 复制代码
    import React from 'react'
    import { Navigate } from 'react-router-dom'
    import BeforeEach from './BeforeEach'
    import ExRouter from './ExRouter'
    
    // 懒加载
    const lazyload = (path: string) => {
      // 加载组件
      let Component=React.lazy(()=>{return import (`@/${path}`)})
      // 返回渲染
      return (
        <React.Suspense fallback={<>请等待·····</>}>
          <Component />
        </React.Suspense>
      )
    }
    
    // 基础路由
    const baseRoutes: Record<string, any>[] = [
      {
        path: '/home',
        element: lazyload('views/home'),
      },
      {
        path: '/user',
        element: lazyload('views/user'),
      },
      {
        path: '/layout',
        redirect: '/layout/home',
        element: lazyload('layouts/BaseLayout'),
        children: [
          {
            path: '/layout/home',
            redirect: '/layout/home/home1',
            element: lazyload('views/home'),
            children: [
              {
                path: '/layout/home/home1',
                element: lazyload('views/home')
              }
            ]
          }
        ]
      }
    ]
    
    // 路由列表
    const routes: Record<string, any>[] = [
      ...baseRoutes,
      {
        path: "/404",
        element: (<>页面地址不存在</>),
      },
      { path: "/", element: <Navigate to="/home" /> },
      { path: "*", element: <Navigate to="/404" /> },
    ]
    
    // 加载配置式路由
    function Router () {
      return (
        <BeforeEach>
          {/* 加载所有路由 */}
          {/* { useRoutes(props.routes) } */}
          {/* 加载所有路由,并扩展路由配置 */}
          <ExRouter routes={routes}></ExRouter>
        </BeforeEach>
      )
    }
    
    // 导出
    export default Router
相关推荐
古茗前端团队2 天前
由 key 引发的思考
前端·javascript·react.js
用户298698530145 天前
React 前端将 Excel 工作表导出为图片的技术实践
javascript·react.js·excel
終不似少年遊*6 天前
【安全业务Agent】从场景到编排
python·react.js·ai·langchain·agent·安全架构·工作流
JavaPub-rodert7 天前
从零搭建通用管理后台:ShiyuAdmin 的 Go、React 与 RBAC 实践
开发语言·react.js·golang
Highcharts.js7 天前
React 中原生支持使用 JSX 组件配置自定义表格 Highcharts Grid
前端·javascript·react.js·前端框架·jsx·highcharts·自定义表格
JudithHuang7 天前
React 嵌套路由与布局
前端·react.js·arcgis·react·react router
前端小D7 天前
React Native项目开发(iOS侧为例)
javascript·react native·react.js
志尊宝8 天前
AI原生前端开发(042):AI辅助的路由设计与优化
javascript·react.js·ai-native
znsoft9 天前
MaClaw(码卡龙)技术拆解:一个 Go + React 的可自进化智能体平台
开发语言·react.js·golang
濮水大叔9 天前
React/Next.js 生态里,有没有 CabloyJS 这样的全栈框架?
react.js·全栈·next.js