javascript - 使用 react-router-dom V6 浏览子路由
问题描述
我同时使用 react-router-dom V6
和Routes
,useRoute
因此,在该站点中,主要路线如下:
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/
替换为:admin
dashboard
发生了什么:
http://localhost:3000/admin => http://localhost:3000/dashboard
预期:
http://localhost:3000/admin => http://localhost:3000/dashboard/app
解决方案
我已将第一个子路径中的 '/' 替换为 '',它对我有用。像这样的东西:
return useRoutes([
{
path: "dashboard",
children: [
{ path: "", element: <Navigate to="dashboard/app" replace /> },
{ path: "app", element: <DashboardApp /> },
{ path: "user", element: <User /> }
]
}
]);
这是简单的应用程序工作示例
推荐阅读
- jenkins - Declare configFileProvider only once in JenkinsFile and reference from all stages
- postgresql - 固件:创建 Postgresql
- c++ - Static link boost library with shared library in CMakeLists.txt
- javascript - Javascript:需要向表格中的按钮形式添加一个选项,允许您只选择一个,将其添加到计数器并遵守某些逻辑
- c++11 - QComboBox 具有与 QMessageBox 无关的行为
- c# - 单击imageView时Listview删除项目
- kubernetes - 如何在 Kubernetes 中设置 HTTPS 负载均衡器
- c++ - 使用 long_options 解析具有任意数量 required_arguments 的选项
- php - PHP - 多维关联数组中的显式键
- c# - CMS 版本 2.2 SHA256WithRSAEncryption