React如何在Menu组件中正确获取路由路径中的id参数?
问题原因
你的Menu组件位于<Routes>组件外部,没有被任何具体的<Route>组件包裹,因此React Router不会为它匹配目标路由/business/:id的参数,只会返回通配符匹配的结果{ *: "business/6" }。而SomePage组件是/business/:id路由的渲染元素,处于该路由的上下文内,所以能正常获取useParams()返回的{ id: 6 }。
解决方案
通过useLocation获取当前路径,结合matchPath手动匹配目标路由,从而提取正确的参数:
在Menu组件中添加以下代码:
import { useLocation, matchPath } from 'react-router-dom'; function Menu() { const location = useLocation(); // 匹配目标路由规则 const routeMatch = matchPath('/business/:id', location.pathname); // 获取参数,若当前路径不匹配则params为undefined const { id } = routeMatch?.params || {}; // 这里可以使用id参数做后续逻辑处理 console.log(id); // 输出6(当路径为/business/6时) return ( // 你的Menu组件内容 ); }
为什么之前的尝试没生效?
如果你之前用过matchPath但没成功,可能是传入的参数不正确。确保第一个参数是路由规则字符串(如/business/:id),第二个参数是当前的路径字符串(通过useLocation()获取的pathname),而不是直接传入location对象。
备选方案
如果你的Menu需要在多个路由下获取不同参数,可以定义所有需要匹配的路由规则数组,循环匹配:
import { useLocation, matchPath } from 'react-router-dom'; const ROUTES = [ '/business/:id', '/user/:userId', // 其他需要匹配的路由规则 ]; function Menu() { const location = useLocation(); const matchedRoute = ROUTES.find(route => matchPath(route, location.pathname)); const params = matchedRoute ? matchPath(matchedRoute, location.pathname)?.params : {}; console.log(params); // 匹配到对应路由时返回对应的参数对象 return ( // 你的Menu组件内容 ); }
内容的提问来源于stack exchange,提问作者viko
相关产品推荐
相关产品推荐

