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

React Router v6嵌套路由访问子路由时父子组件同时渲染问题

问题解决方法

核心原因

react-router-dom v6的嵌套路由默认设计为:父路由对应的组件会始终渲染,子路由对应的组件会渲染到父组件内<Outlet>标记的位置,你的代码中DashboardHomeView同时包含了自身首页内容和<Outlet>,所以访问子路由时会同时出现父组件内容和子组件内容。

方案1:改为平级路由(无需公共布局场景)

如果不需要/dashboard前缀的路由共享公共布局,直接将嵌套路由改为平级即可:
修改AppRouter.js中的路由配置:

// 省略其他import
const AppRouter = () => {
  return (
    <div>
      <Navbar />
      <Routes>
        <Route path="/" element={<HomeView />} />
        {/* 取消嵌套,改为平级路由 */}
        <Route path="dashboard" element={<DashboardHomeView />} />
        <Route path="dashboard/employee" element={<EmployeeHomeView />} />
        <Route path="dashboard/accounting" element={<AccountingHomeView />} />
        <Route path="/login" element={<LoginView />} />
      </Routes>
    </div>
  );
};

修改后可删除DashboardHomeView中的<Outlet>组件。

方案2:保留嵌套结构,使用index路由(需要公共布局场景)

如果后续需要给所有/dashboard前缀的路由加公共布局(比如侧边栏、面包屑),可以保留嵌套结构,将DashboardHomeView的首页内容移到index路由中:
第一步:修改AppRouter.js,新增index子路由

<Route path="dashboard" element={<DashboardHomeView />}>
  {/* index路由匹配/dashboard路径 */}
  <Route index element={<h1>DashboardHomeView</h1>} />
  <Route path="employee" element={<EmployeeHomeView />} />
  <Route path="accounting" element={<AccountingHomeView />} />
</Route>

第二步:修改DashboardHomeView.js,仅保留<Outlet>作为子路由渲染出口

import { Outlet } from "react-router-dom";

const DashboardHomeView = function () {
  return (
    <>
      {/* 后续可在此处添加所有dashboard路由共享的公共布局 */}
      <Outlet />
    </>
  );
};

export default DashboardHomeView;

内容的提问来源于stack exchange,提问作者Emma R.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:15:08