[英]is there a way to nest routes in react
I was wondering if there is a way to nest routes in react in that Navbar
is to become the parent component of dashboard and properties我想知道是否有办法在反应中嵌套路由,
Navbar
将成为仪表板和属性的父组件
<Router>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/login' element={<Login />} />
<Route path='/signup' element={<Signup />} />
<div>
<Navbar />
<div>
<Route path='/dashboard' element={<Dashboard />} />
<Route path='/properties' element={<Dashboard />} />
</div>
</div>
</Routes>
</Router>
Just like you would do in Vue router就像你在 Vue 路由器中所做的一样
const routes = [
{
path: '/user/:id',
component: User,
children: [
{
// UserProfile will be rendered inside User's <router-view>
// when /user/:id/profile is matched
path: 'profile',
component: UserProfile,
},
{
// UserPosts will be rendered inside User's <router-view>
// when /user/:id/posts is matched
path: 'posts',
component: UserPosts,
},
],
},
]
Yes you can.是的你可以。 If you are using React Router v6 the newest one.
如果你使用的是最新的 React Router v6。 You can do it like this.
你可以这样做。
<Route path='/user/:id'>
<Route path='/profile' element={<UserProfile />}
<Route path='/posts' element={<UserPosts />}
</Route>
This means that when you go to /user/1ans5us/profile it will render the UserProfile for the user with the id of '1ans5us'这意味着当您转到 /user/1ans5us/profile 时,它将为 id 为“1ans5us”的用户呈现 UserProfile
Yes, create a layout route that renders the Navbar
component and an Outlet
for nested routes.是的,创建一个呈现
Navbar
组件的布局路由和一个嵌套路由的Outlet
。
Example:例子:
import { Outlet } from 'react-router-dom';
const NavbarLayout = () => (
<>
<Navbar />
<Outlet />
</>
);
export default NavbarLayout;
... ...
import NavbarLayout from '../path/to/NavbarLayout';
...
<Router>
<Routes>
<Route path='/' element={<Home />} />
<Route path='/login' element={<Login />} />
<Route path='/signup' element={<Signup />} />
<Route element={<NavbarLayout />}>
<Route path='/dashboard' element={<Dashboard />} />
<Route path='/properties' element={<Dashboard />} />
</Route>
</Routes>
</Router>
If you wanted to achieve the same thing using a routes config object:如果您想使用路由配置对象来实现相同的目的:
const appRoutes = [
{
path: "/",
element: <Home />,
},
{
path: "/login",
element: <Login />,
},
{
path: "/signup",
element: <Signup />,
},
{
element: <NavbarLayout />,
children: [
{
path: "/dashboard",
element: <Dashboard />,
},
{
path: "/properties",
element: <Dashboard />,
},
],
},
];
... ...
import { useRoutes } from 'react-router-dom';
import appRoutes from '../path/to/appRoutes';
...
const routes = useRoutes(appRoutes);
...
return (
...
{routes}
...
);
Documentation:文档:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.