react 多级路由 子路由切换

2,192 阅读2分钟

  更新2022/02/25 见文末


需求案例:

1.当我们在后台管理页面  左侧菜单栏的情况下 

2.点击左侧菜单栏 路由变化 右侧内容区域变化 

如图: 点击分布式表单出现右侧内容 分布式表单步骤条

​ 

3.第一步的路由 为 "form/step-form/step1"

4.当我们输入完成验证通过 点击下一步 路由 为 "form/step-form/step2"

4.当我们 点击继续 路由 为 "form/step-form/step3"

需求简化就是一个 第三级菜单的跳转 

 文件目录如下:

 路由如下:

{
    path: '/step-form',
    name: '分布式表单',
    icon: <DashboardOutlined />,
    //重点
    exact: false,
    hideChildrenInMenu: true,
    component: lazy(() => import('@/pages/step-form/index')),
    // 不用于匹配 用于给下一级菜单提供数据
    routes: [
      {
        name: '第一步',
        path: '/step1',
        component: lazy(() => import('@/pages/step-form/step1')),
      },
      {
        name: '第二步',
        path: '/step2',
        component: lazy(() => import('@/pages/step-form/step2')),
      },
      {
        name: '第三步',
        path: '/step3',
        component: lazy(() => import('@/pages/step-form/step3')),
      },
    ],
  },

重点:exact: false  如果为 true,则只有在位置完全匹配时才应用激活类/样式。

如果这里 父路由 path: '/step-form' 的路由  exact 为 true的精确匹配 

请求/step-form/step1的时候 不会匹配他的/step-form

如果这里 父路由 path: '/step-form' 的路由  exact为false 的模糊匹配

请求/step-form/step1的时候 不会匹配他的/step-form/step1  而是直接到了/step-form页面

我们这里的目的  就是在请求子路由的时候 直接被父路由拦截掉

import { WauPageContainer, Card, Layout } from '@wii-fe/wau';
import { Switch, Route, Router, Link } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import NotMatch from '@/components/not-match';
import { RouteConfig } from '@/interfaces/route';

const StepForm = (_props: any) => {
 // 定义父级路由 createBrowserHistory
  const historyBase = createBrowserHistory({
    basename: '/step-form',
  });
 // 获取子路由菜单  
  const currDirRoutes = _props.routes;
  console.log('currDirRoutes',currDirRoutes)
  return (
    <WauPageContainer>
    // 重点
      <Router history={historyBase}>
        <Card>
         // 遍历路由链接
          {currDirRoutes?.map((e: RouteConfig) => (
            <Link key={e.path} to={e.path || '/'}>
              {e.name}/
            </Link>
          ))}
        </Card>
        <Layout>
          <Switch>
         // 遍历组件
            {currDirRoutes?.map((e: RouteConfig) => (
              <Route key={e.path} {...e} component={e.component} />
            ))}
            // 没有匹配成功就返回404
            <Route path="*">
              404
            </Route>
          </Switch>
        </Layout>
      </Router>
    </WauPageContainer>
  );
};
export default StepForm;

basename: string

所有位置的基准 URL。basename 的正确格式是前面有一个前导斜杠,但不能有尾部斜杠。

一定要用router basename 包裹着子路由

<Router basename="/step-form">
  <Link to="/step1" />
</Router>

上例中的 <Link> 最终将被呈现为:

<a href="/step-form/step1" />

上面获取子路由 console.log  打印的路由子菜单

 页面效果 步骤与路由对应


2022/2.25更新

项目中实际运用出现的问题

多次点击左侧菜单出现了问题,多次点击后,再切换内部菜单,wu xia左侧菜单的history与step表单的history不一致,

根据报错查询后发现源码中提示 // 项目中不能够改变 history 对象

替换方案:

使用父-子-孙的层级绑定,实现路由切换效果,

 删掉router 标签内的内容  用link代替 当然需要 框架支撑多层菜单的层层传递