• 探索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 数组中继续添加路由配置即可。

  • 相关阅读:
    Python基础复习-面向对象的编程
    社区驱动开发:技术选型的另类浅析
    【uniapp】小程序中input输入框的placeholder-class不生效以及解决办法
    基于django的食堂外卖系统的设计与实现
    asp.net core configuration配置读取
    【产品经理修炼之道】- 需求挖掘之员工计件
    如何更改SonarQube的JDK版本
    随机森林计算指标重要性—从决策树到随机森林Python实现
    springboot vue mysql的在线竞拍拍卖系统
    【React Router v6】路由组件传参params/search/state(router v6)
  • 原文地址:https://blog.csdn.net/sky6862/article/details/138172275