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

react-router-dom V6路由嵌套不符合预期问题求助

React Router DOM V6 嵌套路由异常问题解决

问题现象

  • 访问 http://localhost:5173/quotes/pending/123/sections 时,仅显示 <TopBanner />,嵌套的 <Sections /> 组件无法渲染
  • 访问 http://localhost:5173/quotes/sections 时,反而能正常看到 <Sections /> 组件
  • 测试一级嵌套路由 http://localhost:5173/deals/test 时,仅显示 <Deals />,子路由的 <GeneralInformation /> 不显示

相关代码

AppRoutes 组件

export default function AppRoutes() {
  return (
    <Routes>
      <Route
        path="/quotes/*"
        element={
          <ProtectedRoute>
            <Quotes />
          </ProtectedRoute>
        }
      >
        <Route path="pending/:id/*" element={<PendingQuote />} />
      </Route>

      // ... 其他路由

      <Route path="*" element={<ErrorPage />} />
    </Routes>
  )
}

PendingQuote 组件

export default function PendingQuote() {
  const { id } = useParams()
  console.log("ID from params:", id)
  return (
    <>
      <TopBanner />
      <Routes>
        <Route path="general-information" element={<GeneralInformation />} />
        <Route path="sections" element={<Sections />} />
      </Routes>
    </>
  )
}

简化后的 Quotes 组件

import PendingQuote from "./pending/PendingQuote"

export default function Quotes() {
  return (
    <>
      <PendingQuote />
    </>
  )
}

测试用一级嵌套路由

<Route
  path="/deals/*"
  element={
    <ProtectedRoute>
      <Deals />
    </ProtectedRoute>
  }
>
  <Route path="test" element={<GeneralInformation />} />
</Route>

问题原因

React Router DOM V6 中,嵌套路由的子路由内容必须通过父路由组件中的 <Outlet /> 组件渲染,否则子路由的元素无法挂载到页面上。

当前代码的核心问题:

  1. Quotes 组件直接渲染 PendingQuote,没有为 /quotes/* 的子路由(pending/:id/*)提供 <Outlet />,导致路由上下文无法传递,PendingQuote 内部的嵌套路由无法匹配正确路径
  2. Deals 组件同理,缺少 <Outlet />,使得 /deals/test 的子路由内容无法显示

解决方案

1. 为父组件添加 Outlet

修改 Quotes 组件,用 <Outlet /> 替代直接渲染 PendingQuote:

import { Outlet } from 'react-router-dom'

export default function Quotes() {
  return <Outlet />
}

修改 Deals 组件,同样添加 Outlet:

import { Outlet } from 'react-router-dom'

export default function Deals() {
  return <Outlet />
}

2. 优化 PendingQuote 中的嵌套路由(可选)

可以为 PendingQuote 添加默认路由,确保访问 /quotes/pending/:id/ 时显示默认内容:

import { Routes, Route, useParams } from 'react-router-dom'

export default function PendingQuote() {
  const { id } = useParams()
  console.log("ID from params:", id)
  return (
    <>
      <TopBanner />
      <Routes>
        <Route index element={<GeneralInformation />} />
        <Route path="general-information" element={<GeneralInformation />} />
        <Route path="sections" element={<Sections />} />
      </Routes>
    </>
  )
}

3. 验证效果

完成修改后:

  • 访问 http://localhost:5173/quotes/pending/123/sections 会正常显示 <TopBanner /> 和 <Sections />
  • 访问 http://localhost:5173/deals/test 会正常显示 <GeneralInformation />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 13:35:53