• 探索React Router:实现动态二级路由


    在这里插入图片描述

    我有一个路由配置的二维数组,想根据这个数组结合路由组件来动态生成路由,应该怎么样实现。在 React Router 6 中渲染二级路由的方式跟 React Router 65相比有一些变化,但核心思路仍然是利用 Route 组件和路由嵌套的方式。下面是具体的步骤:

    1. 定义路由数组
    const routes = [
      {
        path: '/',
        element: <Home />
      },
      {
        path: '/about',
        element: <About />
      },
      {
        path: '/products',
        element: <Products />,
        children: [
          {
            path: 'list',
            element: <ProductList />
          },
          {
            path: 'details/:id',
            element: <ProductDetails />
          }
        ]
      }
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    注意,这里我们使用 element 属性代替了之前版本中的 component 属性。

    1. App.js 中使用 RoutesRoute 组件渲染路由
    import { BrowserRouter, Routes, Route } from 'react-router-dom';
    
    function App() {
      return (
        <BrowserRouter>
          <Routes>
            {routes.map((route, index) => (
              <Route
                key={index}
                path={route.path}
                element={<route.element />}
              >
                {route.children && route.children.map((child, idx) => (
                  <Route
                    key={idx}
                    path={`${route.path}/${child.path}`}
                    element={<child.element />}
                  />
                ))}
              </Route>
            ))}
          </Routes>
        </BrowserRouter>
      );
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在上面的代码中,我们使用 Routes 组件包裹所有的 Route 组件。对于每个路由对象,我们渲染一个 Route 组件,并将 pathelement 属性传入。如果该路由对象包含子路由,我们使用嵌套的 Route 组件来渲染子路由。

    注意,在 React Router 6 中,我们需要使用字符串模板字面量语法 `${route.path}/${child.path}` 来拼接父路径和子路径。

    1. 在组件中渲染子路由
      对于需要渲染子路由的组件,例如 Products,我们可以使用 Outlet 组件作为子路由的占位符。
    import { Outlet } from 'react-router-dom';
    
    function Products() {
      return (
        <div>
          <h1>Products</h1>
          <Outlet />
        </div>
      );
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    Outlet 组件会根据当前的 URL 路径渲染与之匹配的子路由。

    通过上述步骤,我们就可以在 React Router 6 中动态渲染二级路由了。如果有更深层次的嵌套路由,只需要在 children 数组中继续添加路由配置即可。

  • 相关阅读:
    three.js/webgl实现室内模型行走
    VR全景技术在城市园区发展中有哪些应用与帮助
    Nacos配置管理-微服务配置拉取
    ES6学习笔记
    使用 Flask-WTF 防止跨站请求攻击(CSRF):一份全面指南
    【目标检测】RCNN算法实现
    ES相关问题
    ctfhub-web-warmup
    ios小程序蓝牙发送信息失败,报10004
    kibana启动报错
  • 原文地址:https://blog.csdn.net/sky6862/article/details/138172275