react - 多层级嵌套路由支持

routerCofing配置


  {
    path: '/route1/someModel',
    children: [
      {
        path: '/route2',
        component: RouteBase.Cps1,
        children: [
          {
            path: '/route3',
            component: RouteBase.Cps2,
            children: [
              {
                path: '/route4',
                component: RouteBase.Cps3,
              },
            ]
          },
        ]
      },
      {
        path: '/route5', // 退货
        component: RouteBase.Cps4
      }
    ]
  },

router - index

  // 返回路由
  const RouteItem = props => {
    const { redirect, path, component, key } = props
    if (redirect) {
      return <Redirect exact key={key} from={path} to={redirect} />
    }
    return <Route exact key={key} component={component} path={path} />
  }

  // eslint-disable-next-line no-array-constructor
  let Routes: any = new Array()

  // 获取子路由

  const loopRoute = (route, i, pre_path?: string) => {
    return route.children.forEach((routeChild, idx) => {
    let __path = pre_path + routeChild.path
      const { redirect, component, children } = routeChild
      if (children && children.length) {
        // 递归获取子路径
        if (component) {
          Routes = Routes.flat()
          Routes.push(RouteItem({
            key: `${i}-${idx}`,
            redirect,
            path: __path,
            component: component
          }))
        }
        loopRoute(routeChild, idx, __path)
      } else {
        Routes.push( RouteItem({
          key: `${i}-${idx}`,
          redirect,
          path: __path,
          component: component
        }))
      }
    })
  }

  routes.forEach((route: any, key) => {
    return Array.isArray(route.children) && route.children.length
      ?  loopRoute(route, key, route.path)
      :  Routes.push(RouteItem({ key, ...route }))
  })

// 使用

<Switch>
  <Route exact path='/login' component={Login} />
  {Routes}
</Switch>

猜你喜欢

转载自www.cnblogs.com/mapleChain/p/12632719.html
今日推荐