如何在React Router通配符路由中正确使用Link组件?
React Router v7 避免相对路径叠加问题的解决方案
你的问题出在workspace/:spaceId/*这个带通配符的路由上:当你在该路由的组件内使用<Link to="setting">时,React Router会将setting作为当前路径的子路径追加。比如当前路径是/homepage/workspace/1/setting,点击链接后就会变成/homepage/workspace/1/setting/setting,多次点击就会不断叠加。
以下是几种无需写绝对路径的解决方法:
方法一:使用上级相对路径
直接用../setting作为链接目标,这样每次点击都会先回到workspace/:spaceId层级,再追加setting,无论当前处于哪级子路径,最终都会定位到/homepage/workspace/[spaceId]/setting:
<Link to="../setting">To space setting</Link>
方法二:通过useMatch获取父路由路径
利用useMatch钩子匹配当前的父路由(workspace/:spaceId/*),拿到父路由的路径后拼接setting,确保跳转路径始终基于父路由:
import { useMatch, Link, Routes, Route } from 'react-router'; // 把workspace的element抽成组件 const WorkspaceComponent = () => { const match = useMatch('workspace/:spaceId/*'); return ( <div> <Link to={`${match.pathname}/setting`}>To space setting</Link> <Routes> <Route path="setting" element={<div>空间设置页面</div>} /> </Routes> </div> ); }; // 路由配置里替换原来的element { path: 'workspace/:spaceId/*', element: <WorkspaceComponent />, }
方法三:利用useLocation截取父路径
通过useLocation获取当前路径,手动截取到workspace/:spaceId层级后拼接setting,适合需要更精细路径控制的场景:
import { useNavigate, useLocation, Routes, Route } from 'react-router'; const WorkspaceComponent = () => { const navigate = useNavigate(); const location = useLocation(); const goToSetting = () => { // 截取路径到workspace/:spaceId部分(根据你的路由层级调整slice的参数) const parentPath = location.pathname.split('/').slice(0, 4).join('/'); navigate(`${parentPath}/setting`); }; return ( <div> <button onClick={goToSetting}>To space setting</button> <Routes> <Route path="setting" element={<div>空间设置页面</div>} /> </Routes> </div> ); };
其中方法一最简单直接,完全满足你的需求,无需额外引入钩子或复杂逻辑。
内容的提问来源于stack exchange,提问作者DisLido
相关产品推荐
相关产品推荐

