Ste*_*nos 4 reactjs react-router
如何将完整路径与路径“users/:id/settings”匹配,但同时仅渲染每个路径中的组件:
<Route path="users" element={<h2>LIST PROJECTS</h2>}>
<Route path=":id" element={<h2>PROJECT id</h2>}>
<Route path="settings" element={<h2>PROJECT SETTINGS</h2>} />
</Route>
</Route>
Run Code Online (Sandbox Code Playgroud)
我已经通过以下方式解决了这个问题:
- / // Level 1 routes index route
- users // level 1 route
- / // Level 2 routes index route
- :id // level 2 route
- settings // level 2 route
- posts // level 1 route
- / // Level 2 routes index route
- :id // level 2 route
- settings // level 2 route
- ...
Run Code Online (Sandbox Code Playgroud)
我将 1 级路由视为我的应用程序的数据集合(用户、帖子等),将 2 级路由视为与更高级别集合中的特定项目相关的任何子路由(:userId、设置等)
<Outlet />react-router-v6中的组件作为每个父路由中要渲染的元素。Outlet负责渲染该索引下子路由的所有子组件,因此我们element={<Outlet />}在索引路由上使用,而不是直接渲染 React 组件。下面是一个使用索引路由渲染 Outlet 组件的示例:
<Route path="users"element={ <Outlet /> } >
<Route path="/" element={<h2>LIST USERS</h2>} />
<Route path=":id" >
<Route path="/" element={<React.Fragment>
<h2>USER id</h2>
<Outlet />
</React.Fragment>} />
<Route path="settings" element={<h2>USER SETTINGS</h2>} />
</Route>
</Route>
Run Code Online (Sandbox Code Playgroud)
这是使用 useRoutes 钩子的更完整的方法,通过它我们可以更干净地编写相同的配置作为简单的 JS 对象:
import {Outlet, useRoutes} from "react-router-dom"
const App = () => {
let routeElement = useRoutes([
{
path: "/",
element: <GlobalPageTemplate />,
children: [
{
path: "users",
element: <Outlet />,
children: [
{ path: "/", element:<h1>LIST USERS <h1/> },
{
path: "/:id",
children: [
{ path: "/", element: <h1>USER ID</h1> },
{ path: "/settings", element: <h1>USER SETTINGS</h1> },
],
},
],
},
{
path: "posts",
element: <Outlet />,
children: [
{ path: "/", element: <h1>LIST POSTS</h1> },
{
path: "/:id",
children: [
{ path: "/", element: <h1>POST ID</h1> },
{ path: "/settings", element: <h1>POST SETTINGS</h1> },
],
},
],
},
{
path: "teams",
element: <Outlet />,
children: [
{ path: "/", element: <h1>LIST TEAMS</h1> },
{
path: "/:id",
children: [
{ path: "/", element: <h1>TEAMS ID</h1> },
{ path: "/settings", element: <h1>TEAM SETTINGS</h1> },
],
},
],
},
]
}
]);
return routeElement
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6130 次 |
| 最近记录: |