我有route
<Routes>
<Route path="/main" element={<Main />}>
<Route path=":page" element={<><PostList /><Pagination /></>} />
<Route path="post/:id" element={<PostCurrent />} />
<Route path="login" element={<SignIn />} />
</Route>
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="post-form" element={<PostForm />} />
<Route path="post-list" element={<PostListDashBoard />} />
</Route>
</Route>
<Route path="*" element={<Navigate to="/main/0" replace />} />
</Routes>
如果您想在"/:page"
和"/post/:id"
路由上同时渲染SignIn
组件,那么创建一个布局路由来渲染SignIn
,并为嵌套的Route
组件创建一个Outlet
。
的例子:
import { Outlet } from 'react-router-dom';
const MainLayout = () => (
<>
<Outlet />
<SignIn />
</>
);
…
<Routes>
<Route path="/main" element={<Main />}>
// Layout route rendering Signin w/ nested routes
<Route element={<MainLayout />}>
<Route
path=":page"
element={<><PostList /><Pagination /></>}
/>
<Route path="post/:id" element={<PostCurrent />} />
</Route>
<Route path="login" element={<SignIn />} />
</Route>
<Route element={<ProtectedRoute />}>
<Route path="/dashboard" element={<Dashboard />}>
<Route path="post-form" element={<PostForm />} />
<Route path="post-list" element={<PostListDashBoard />} />
</Route>
</Route>
<Route path="*" element={<Navigate to="/main/0" replace />} />
</Routes>