首页 > 解决方案 > 使用 react-router-dom V6 浏览子路由

问题描述

我同时使用 react-router-dom V6RoutesuseRoute因此,在该站点中,主要路线如下:

export default function App() {
  return (

    <Routes>
      <Route path="/" element={<Components />} />
      <Route path="admin" element={<AdminApp />} />
    </Routes>


  )
}

如上所示,第二个 Route 的元素是<AdminApp />该元素来自以下内容:

export default function AdminApp() {
  return useRoutes([
    {
      path: '/dashboard',
      element: <DashboardLayout />,
      children: [
        { path: '/', element: <Navigate to="/dashboard/app" replace /> },
        { path: 'app', element: <DashboardApp /> },
        { path: 'user', element: <User /> },
        { path: 'products', element: <Products /> },
        { path: 'blog', element: <Blog /> }
      ]
    },
    {
      path: '/',
      element: <LogoOnlyLayout />,
      children: [
        { path: 'login', element: <Login /> },
        { path: 'register', element: <Register /> },
        { path: '404', element: <NotFound /> },
        { path: '/', element: <Navigate to="/dashboard" /> },
        { path: '*', element: <Navigate to="/404" /> }
      ]
    },

    { path: '*', element: <Navigate to="/404" replace /> }
  ]);
}

因此,每当我调用路线/admin时,屏幕上都不会显示任何内容,并且console log我会收到此警告

index.tsx:90 You rendered descendant <Routes> (or called `useRoutes`) at "/admin" (under <Route path="admin">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render.

Please change the parent <Route path="admin"> to <Route path="admin/*">

我已更改 <Route path="admin" element={<AdminApp />} />为, <Route path="admin/*" element={<AdminApp />} />因此警告消失了,但是当我导航到该路线时页面显示为空白,并将 URL 中的单词admin/替换为:admindashboard

发生了什么:

http://localhost:3000/admin => http://localhost:3000/dashboard

预期:

http://localhost:3000/admin => http://localhost:3000/dashboard/app

标签: javascriptreactjsreact-router-dom

解决方案


我已将第一个子路径中的 '/' 替换为 '',它对我有用。像这样的东西:

return useRoutes([
    {
      path: "dashboard",
      children: [
        { path: "", element: <Navigate to="dashboard/app" replace /> },
        { path: "app", element: <DashboardApp /> },
        { path: "user", element: <User /> }
      ]
    }
  ]);

是简单的应用程序工作示例


推荐阅读