React使用React-router时如何在带动态id的/page子页面隐藏菜单
问题原因
你当前的判断逻辑是直接将location.pathname和路由定义的模板字符串/page/:id?做全等比较,但实际访问带参数的路径时(比如/page/123),location.pathname的值是真实的路径字符串而非路由模板,因此匹配失败,菜单无法隐藏。
解决方案
下面提供两种常用实现方案:
方案1:前缀匹配(简单快速)
直接判断路径是否符合/page相关的规则,代码修改如下:
<Router> {location.pathname === "/welcome" || location.pathname === "/login" || location.pathname === "/registration" || // 新增匹配规则:覆盖不带参数的/page和带参数的/page/xxx场景 location.pathname === "/page" || location.pathname.startsWith("/page/") ? null : ( <div> <Menu /> <Mobile /> </div> )} {/* 下方Switch路由部分保持原有代码不变 */} <Switch> <Route exact path="/welcome" component={Welcome} /> <Route exact path="/login" component={Login} /> <Route exact path="/page/:id?" component={Page} /> <Route exact path="/settings" component={Settings} /> <Route exact path="/dash" component={New}/> <Route exact path="/customize/:id?" component={Home} /> <Route exact path="/" component={Dash} /> <Route component={New} /> </Switch> </Router>
方案2:matchPath精准匹配(更严谨,推荐)
使用React Router官方提供的matchPath工具方法,直接复用已定义的路由模板做匹配,不会出现前缀匹配可能导致的误判问题:
- 首先引入依赖:
import { matchPath } from 'react-router-dom';
- 修改判断逻辑:
<Router> {location.pathname === "/welcome" || location.pathname === "/login" || location.pathname === "/registration" || // 直接复用路由模板匹配,和下方Route定义的规则完全一致 matchPath(location.pathname, { path: "/page/:id?", exact: true }) ? null : ( <div> <Menu /> <Mobile /> </div> )} {/* 下方Switch路由部分保持原有代码不变 */} </Router>
该方案匹配逻辑和React Router内部路由匹配逻辑完全一致,后续调整/page路由的参数规则时,只需要同步修改matchPath的配置即可,维护成本更低。
内容的提问来源于stack exchange,提问作者AlyaKra
相关产品推荐
相关产品推荐

