You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

react-router-dom v5路由如何按顺序配置实现正确匹配?

问题根因

React Router v5 的 <Switch> 组件遵循从上到下的前缀匹配规则:只要当前访问路径和配置的路由前缀匹配,就会停止后续匹配,直接渲染当前路由对应的组件。
你当前子路由配置中,/dashboard/buyList 放在了更精确的 /dashboard/buyList/new 前面,访问后者时会先匹配到前者的前缀规则,所以只会渲染BuyList组件。此外你还存在两处额外的路由配置错误会加剧匹配异常。

调整方案
  • 调整子路由排列顺序:将路径更长、匹配规则更精确的路由放在前面,前缀类短路径路由放在后面
  • 给短路径路由添加exact属性:确保/dashboard/buyList只有完全匹配时才触发渲染
  • 删除Dashboard组件内的冗余<Router>声明:根组件已经全局声明了<BrowserRouter>,子组件不需要重复声明Router,否则会导致路由上下文隔离,无法正常匹配子路由
  • 修正参数路由的路径拼接错误:/dashboard/buyList${ids.id} 缺少斜杠,需要改为/dashboard/buyList/${ids.id},否则会拼接出/dashboard/buyList123这类不符合预期的路径
调整后Dashboard子路由参考代码
<>
    <Navbar />
    <Switch>
        {/* 精确长路由放在最前 */}
        <Route exact path='/dashboard/buyList/new' component={NewBuy} />
        <Route path={`/dashboard/buyList/${ids.id}`} component={BuyInfo}/>
        {/* 短路径路由加exact,放在同前缀路由后面 */}
        <Route exact path={`/dashboard/buyList`} component={BuyList} />
        <Route path='/dashboard/showAddress' component={ShowAddress} exact/>
        <Route path='/dashboard/qrScanner' component={QrScanner} exact/>
        <Route path='/dashboard/productList' component={ProductList} exact/>
        <Route path='/dashboard/productListCode' component={ProductListCode} exact/>
        <Route path='/dashboard/deliveryScanner' component={DeliveryScanner} exact/>
        <Route path='/dashboard' component={DashboardDetail} exact/>
        <Route path="/404" component={NotFound} />
    </Switch>
</>

内容的提问来源于stack exchange,提问作者bardia riahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:15:00