React Router中使用通配符*时useParams返回结果异常的原因与解决
React Router useParams 通配符参数异常问题解决
当前访问 /appid/page2 时,Page2 组件的 useParams() 返回 {"appId":"appid", "*":""},而访问 /appid/page3 时 Page3 组件返回 {"appId":"appid", "*":"page3"},需要让 Page2 组件也能获取到 {"appId":"appid", "*":"page2"}。
问题原因
问题出在 Application 组件内的路由配置逻辑:
- Page2 的路由是
<Route path="/page2/*" element={<Page2 />} />,末尾的*用于捕获/page2之后的子路径(比如/page2/sub),但当前访问的/appid/page2没有后续子路径,内层通配符捕获空值的同时,父路由:appId/*的通配符被内层路由匹配消耗,导致 Page2 拿到的*参数为空。 - Page3 的路由是
<Route path="/page3" element={<Page3 />} />,没有内层通配符,父路由的:appId/*直接捕获page3作为通配符参数的值。
解决方案
修改 Application 组件中的 Page2 路由,去掉路径末尾的 *,让父路由的通配符正确捕获 page2:
function Application() { return ( <> 1 <Routes> <Route path="/" element={<Page1 />} /> {/* 移除 /page2 后的通配符 */} <Route path="/page2" element={<Page2 />} /> <Route path="/page3" element={<Page3 />} /> </Routes> </> ); }
修改后,访问 /appid/page2 时,父路由 :appId/* 会将 page2 作为通配符参数的值,Page2 组件通过 useParams() 就能拿到 {"appId":"appid", "*":"page2"},和 Page3 的行为一致。
如果后续需要给 Page2 添加嵌套子路由,可以调整为以下结构,既保留 Page2 的通配符参数,又支持子路由:
function Application() { return ( <> 1 <Routes> <Route path="/" element={<Page1 />} /> {/* 将 Page2 作为父路由,子路由单独使用通配符 */} <Route path="/page2" element={<Page2 />}> <Route path="*" element={/* 子路由组件 */} /> </Route> <Route path="/page3" element={<Page3 />} /> </Routes> </> ); }
此时访问 /appid/page2 时,Page2 依然能拿到 *: "page2";访问 /appid/page2/sub 时,子路由组件会捕获到 *: "sub"。
内容的提问来源于stack exchange,提问作者gokulsgr
相关产品推荐
相关产品推荐

