前言
近期完成了公司新项目的开发,相关的技术栈都用到了最新版本,react router 也使用了 v6 的版本,所以借这个机会自己再梳理下 react router v5 与 v6 的区别,以及 v6 一些新特性。而在原有项目还是使用老版本 react router 的情况下,不太建议急着直接升级,可能存在较多的改动。
v5 升级 v6 指南
<Switch>
全部换成<Routes>
v5
<BrowserRouter>
<Menu />
<Switch>
<Route component={Home} path="/home"></Route>
<Route component={List} path="/list"></Route>
<Route component={Detail} path="/detail"></Route>
<Route component={Category} path="/category"></Route>
</Switch>
</BrowserRouter>
// Category.tsx
<Switch>
<Route component={CategoryA} path="/category/a"></Route>
<Route component={CategoryB} path="/category/b"></Route>
</Switch>
Switch
组件作用:渲染第一个被 location 匹配到的并且作为子元素的 <Route>
或者 <Redirect>
,它仅仅只会渲染一个路径
v6
<BrowserRouter>
<Menu />
<Routes>
<Route element={<Home />} path="/home"></Route>
<Route element={<List />} path="/list"></Route>
<Route element={<Detail />} path="/detail"></Route>
<Route element={<Category />} path="/category"> {/* children 写法嵌套子路由,path是相对路径 */} <Route element={<CategoryA />} path="a"></Route>
<Route element={<CategoryB />} path="b"></Route>
</Route>
</Routes>
</BrowserRouter>
与 Switch
相比,Routes
的主要优点是:
Routes
内的所有<Route>
和<Link>
的 path 支持相对路由(如果以/
开头的则是绝对路由)。这使得<Route path>
和<Link to>
中的代码更精简、更可预测- 路由基于最佳 path 匹配的,而不是按顺序遍历选择的
- 路由可以嵌套在同一个地方而不必分散在不同的组件中
注意:
- 不能认为
Routes