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

React Router v6不同路由配置不同布局的问题求助

解决方案:React Router v6 多布局路由配置

问题根源

当前配置同时渲染了两个独立的<Routes>组件,每个组件会独立匹配路径。访问/editor时,第一个<Routes>匹配到/editor并渲染EditorPage,第二个<Routes>因未匹配到/或其他指定路径,触发path='*'的NotFoundPage,导致两种布局和页面同时显示。

正确配置方式

方式一:嵌套路由(推荐)

利用React Router v6的<Outlet>组件实现布局与页面的嵌套,结构更清晰,适合复杂场景。

  1. 修改布局组件,替换children为<Outlet>
import { Outlet } from 'react-router-dom';
import type { ReactNode } from 'react';

export type LayoutProps = {
  children?: ReactNode; // 保留可选children,兼容其他场景
}

// MainLayout
const MainLayout: React.FC<LayoutProps> = () => (
  <div className='main-layout'>
    <div className='main-layout__content'><Outlet /></div>
    <FooterComponent />
  </div>
);

// BlankLayout
const BlankLayout: React.FC<LayoutProps> = () => (
  <div className='editor-layout'>
    <div className='editor-layout__content'><Outlet /></div>
  </div>
);
  1. 配置嵌套路由
import { BrowserRouter, Routes, Route } from 'react-router-dom';

<BrowserRouter>
  <MainBarLayout>
    <Routes>
      {/* 使用MainLayout的路由组 */}
      <Route element={<MainLayout />}>
        <Route path='/' element={<IndexPage />} />
        {/* 404路由需放在所有路由最后,避免提前匹配 */}
        <Route path='*' element={<NotFoundPage />} />
      </Route>

      {/* 使用BlankLayout的路由组 */}
      <Route element={<BlankLayout />}>
        <Route path='/editor' element={<EditorPage />} />
        <Route path='/view/*' element={<ViewPage />} />
      </Route>
    </Routes>
  </MainBarLayout>
</BrowserRouter>

方式二:直接组合布局与页面

适合简单场景,直接在路由element中把布局和页面组件组合。

<BrowserRouter>
  <MainBarLayout>
    <Routes>
      <Route path='/' element={<MainLayout><IndexPage /></MainLayout>} />
      <Route path='/editor' element={<BlankLayout><EditorPage /></BlankLayout>} />
      <Route path='/view/*' element={<BlankLayout><ViewPage /></BlankLayout>} />
      {/* 404路由必须放在最后 */}
      <Route path='*' element={<MainLayout><NotFoundPage /></MainLayout>} />
    </Routes>
  </MainBarLayout>
</BrowserRouter>

关键注意点

  • 仅保留一个<Routes>组件,确保路由匹配逻辑唯一。
  • path='*'的404路由必须放在所有路由的最后,避免拦截正常路径的匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 22:13:37