【问题标题】:react-router-dom 6 upgrade help: All component children of <Routes> must be a <Route> or <React.Fragment>react-router-dom 6 升级帮助:<Routes>的所有子组件必须是<Route>或者<React.Fragment>
【发布时间】:2022-01-01 23:52:34
【问题描述】:

我们的应用程序最近更新到 react-router-dom 的 beta 版本,一切都很好。然后当我尝试更新到 6.0.2 时,我收到很多关于 All component children of &lt;Routes&gt; must be a &lt;Route&gt; or &lt;React.Fragment&gt; 的不变错误。这是因为我们的路由定义如下:

Feature.jsx:

export const FeatureRoutes = () => (
  <Routes>
    <Route path="/" element={<Feature1 />} />
    <Route path="/*" element={<NotFound />} />
  </Routes>
);

routes.jsx:

export const routes = [
  {
    path: "feature",
    component: FeatureRoutes,
  },
  /* lots of other routes, defined the same way: <Route> wrapped in a component */
];

App.jsx:

<Routes>
  {routes.map((route) => (
    <Route key={route.path} path={`${pathPrefix}/${route.path}/*`}>
      <route.component />
    </Route>
  ))}
</Routes>

现在这会导致上述错误,因为内部路由(例如 FeatureRoutes)被包装在功能组件中。我尝试返回文字 JSX,但随后又出现了另一个错误。我不知道如何解决这个问题:是完全重写我们如何定义我们的路线的唯一答案吗?我们还有一些路由存储在后端并映射到自定义组件 - 我不知道如何包装这些现在我不允许在 Routes 和 Route 之间有组件。

任何建议表示赞赏。

【问题讨论】:

    标签: react-router react-router-dom


    【解决方案1】:

    我相信一个小的重构会让你的应用重新渲染。

    routes 数组中,将 component 重命名为 Component,以便它可以呈现为 React 组件,即作为正确命名的 React 组件 (PascalCased)。

    const routes = [
      {
        path: "feature",
        Component: FeatureRoutes
      }
      /* lots of other routes, defined the same way: <Route> wrapped in a component */
    ];
    

    当映射routes 时,将Component 渲染到Route 组件的element 属性上as JSX

    <Routes>
      {routes.map(({ path, Component }) => (
        <Route
          key={path}
          path={`${pathPrefix}/${path}/*`}
          element={<Component />}
        />
      ))}
    </Routes>
    

    【讨论】:

      猜你喜欢
      • 2022-10-15
      • 2022-01-01
      • 2022-01-07
      • 2021-12-30
      • 2021-12-20
      • 2022-01-22
      • 1970-01-01
      • 2022-01-01
      相关资源
      最近更新 更多