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

React Router路由未按配置渲染,/account下子路由无对应组件显示

React Router嵌套路由不渲染问题修复方案

问题根因

  • 重复嵌套组件:整个应用仅需在最外层声明一次即可,Account组件内额外声明的会创建独立路由上下文,和上层路由不连通,无法匹配带/account前缀的路径。
  • 子路由路径未补全前缀:你当前写的子路由path为/edit,实际需要匹配的完整路径是/account/edit,路径不匹配自然无法渲染对应组件。
  • 父级路由加exact会阻断子路由匹配:给/account路由加exact属性后,只有路径完全等于/account时才会渲染Account组件,访问/account/edit等子路径时会直接匹配到404。

修复步骤

1. 保留App.js现有路由配置,不要给/account加exact属性

原有App.js的路由逻辑无需改动,保持如下即可:

function Routes() {
  return (
    <Switch>
      <Route path="/" component={Home} exact />
      <Route path="/account" component={Account} />
      <Route render={() => <Route component={Error} />} />
    </Switch>
  );
}

2. 修正Account.js的路由配置

删除Account组件内的,用React Router自动注入的match属性拼接子路由路径,避免硬编码前缀:

const Account = ({ match }) => {
  return (
    <>
      <NavBar />
      <Switch>
        <Route path={`${match.path}/edit`} component={EditAccount} exact />
        <Route path={`${match.path}/myorders`} component={MyOrders} />
        <Route path={`${match.path}/favorites`} component={Favorites} />
      </Switch>
    </>
  );
};

修改完成后访问/account/edit、/account/myorders等路径即可正常渲染对应子组件,导航栏也会保持常驻。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 07:15:04