最近在将项目从React Router v5升级到v6时,遇到了一个令人头疼的路由匹配问题。在使用通配符*时,发现路径匹配逻辑发生了根本性变化。
问题复现
在v5中,我们这样配置路由:
<Route path="/user/*" component={UserComponent} />
但在v6中,这种方式会直接报错。正确的写法应该是:
<Route path="/user/*" element={<UserComponent />} />
精确匹配陷阱
更复杂的问题出现在精确匹配上。比如想要匹配/user/profile但不匹配/user/profile/edit时:
<Route path="/user/profile" element={<Profile />} />
<Route path="/user/profile/*" element={<ProfileEdit />} />
解决方案
关键是要理解v6的useRoutes和Routes组件的匹配逻辑。推荐使用以下方式:
<Routes>
<Route path="/user" element={<UserLayout />}>
<Route index element={<UserHome />} />
<Route path="profile" element={<Profile />} />
<Route path="profile/*" element={<ProfileEdit />} />
</Route>
</Routes>
重要提醒
v6中不再支持exact属性,所有路由都是精确匹配,除非使用通配符。在升级过程中一定要仔细检查所有路由配置,特别是嵌套路由的路径匹配顺序。

讨论