react-router-dom v6 路由嵌套
时间: 2023-08-23 22:14:18 浏览: 160
在React Router v6中,路由嵌套的写法有所改变。以下是一个示例:
```jsx
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import { Outlet } from 'react-router-dom';
const App = () => {
return (
<Router>
<Routes>
<Route path="/app" element={<ThisLayout />}>
<Route path="/" element={<PostsList />} />
<Route path="/singlePostPage/:id" element={<SinglePostPage />} />
</Route>
</Routes>
</Router>
);
};
const PostsList = () => {
// ...
return (
<section>
<h2>posts</h2>
{renderedPosts}
<Outlet /> {/* 子路由渲染位置 */}
</section>
);
};
const SinglePostPage = () => {
// ...
};
const ThisLayout = () => {
// ...
};
export default App;
```
在v6中,我们使用`Routes`组件来定义路由,而不再使用`Switch`组件。在父路由中,我们使用`Route`组件来定义子路由。子路由的元素可以通过`element`属性指定。在子路由的父组件中,我们可以使用`Outlet`组件来渲染子路由的内容。
希望这个例子能帮助你理解React Router v6中的路由嵌套写法。
#### 引用[.reference_title]
- *1* [解决react-router-dom V6路由嵌套时子路由无法显示的问题](https://blog.csdn.net/frank7023/article/details/128913988)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *2* [React Router v6 路由配置,嵌套路由](https://blog.csdn.net/Snow_GX/article/details/123656412)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
- *3* [react-router-dom v6版本 嵌套路由](https://blog.csdn.net/jzh1359314792/article/details/126526047)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down28v1,239^v3^insert_chatgpt"}} ] [.reference_item]
[ .reference_list ]
阅读全文