react-router-dom 嵌套路由

项目中,经常会出现几个页面共用一个组件的情况,而且几个页面的流程是一致的,为了方便页面的管理和后期的维护性,我们需要使用页面嵌套页面的这种形式去开发。

这里用react-router-dom来实现:

首先引入需要用到的组件

import { BrowserRouter as Router, Switch, Route, Redirect } from 'react-router-dom';

然后定义好我们的嵌套路由:

const routerConfig = [{
    path: "/father",
    component: Father,
    children: [
      {
        path: "/child1",
        component: Child1,
        redirect: true
      },
      {
        path: "/child2",
        component: Child2,
      }
    ],
  },
//  ....
]

现在我们写路由:

const RouterComp = props => {
  return (
    <Suspense fallback={<div></div>}>
      <Router children={createRoute(routerConfig)} />
    </Suspense>
  );
}

const createRoute = routes => {
    return (
      <Switch>
        {
          routes.map((route, index) => 
            createFixRoute(route, index)
          )
        }
        <Redirect from='/*' to='/' />
      </Switch>
    );
  };
  //该组件通过递归的方式,将所有route中带有children路由的父路由进行解构,最终用createBasicRoute函数来渲染
  const createFixRoute = (route, index) => {
    const { path, component: RouteComponent, children } = route;
    if (children) {
      return (
        <Route
          key={index}
          path={path}
          children={props => {
            let redirectPath = null;
            return <RouteComponent {...props}>
              <Switch>
                {children.map((child, index2) => {
                  const { path: childPath, redirect } = child;
                  if (redirect){
                    redirectPath = childPath;
                  }
                  return createFixRoute({...child, path: path + childPath}, `${index}-${index2}`);
                })}
                <Redirect from={`${path}`} to={`${path}${redirectPath || children[0].path}`} />
              </Switch>
            </RouteComponent>;
          }}
        />
      );
    } else {
      return createBasicRoute(route, index);
    }
  };

  const createBasicRoute = (route, index) => {    //  最基础的Router 用法
    const { path, component: Component } = route;
    return <Route exact key={index} path={path} component={props => {
      props.history.listen(path => {    //  路由监听
        ...
      });
      return <Component {...props} />;
    }} />;
  };

撒花!!

嵌套路由的写法在当我们有多个页面需要复用组件的时候,优势很大:
1.方便传值,不需要在每个页面重新给复用的组件赋值
2.减少了dom节点的更新,变相地提高了页面的流畅性
3.从路由上就能很清晰地看到每个流程包含的页面
4.优雅!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值