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

React Router Dom v6嵌套路由:URL变更但组件未渲染如何解决?

问题解决:侧边栏Link点击后URL变化但内容区不更新

核心问题

你的代码存在两个关键错误,导致内容展示区无法正常渲染组件:

  1. MainPage中子路由路径错误:App.js已将/main/*路径交由MainPage处理,因此MainPage内的子路由无需再带/main前缀,直接使用相对路径即可。
  2. Dashboard路由属性写错:react-router-dom v6中需用element属性指定渲染组件,你误用了大写的Component;同时index属性的使用位置也不正确。

修改后的MainPage代码

import { Route, Routes, useMatch } from 'react-router-dom';
import { MdDashboard } from "react-icons/md";
import { IoIosSettings } from "react-icons/io";
import { FaUsers, FaUserAstronaut } from "react-icons/fa";
import Sidebar from "../components/Sidebar"
import SidebarItem from "../components/SidebarItem"
import SamplePage from './SamplePage';

const MainPage = () => {
  // 用useMatch自动判断当前路由是否激活,替代手动传active状态
  const isDashboardActive = useMatch("/main/dashboard");
  const isUsersActive = useMatch("/main/users");
  const isProvidersActive = useMatch("/main/providers");
  const isSettingsActive = useMatch("/main/settings");

  return (
    <div className='flex w-full h-full'>
      <Sidebar>
        <SidebarItem icon={<MdDashboard/>} text="Dashboard" path="dashboard" active={isDashboardActive}/>
        <SidebarItem icon={<FaUsers/>} text="Users" path="users" active={isUsersActive}/>
        <SidebarItem icon={<FaUserAstronaut/>} text="Providers" path="providers" active={isProvidersActive}/>
        <SidebarItem icon={<IoIosSettings/>} text="Settings" path="settings" active={isSettingsActive}/>
      </Sidebar>
      <div className='w-full h-dvh bg-black'>
        <Routes>
          {/* 改用相对路径,修正element属性,index设置为默认路由 */}
          <Route index element={<SamplePage title="Dashboard"/>}/>
          <Route path="dashboard" element={<SamplePage title="Dashboard"/>}/>
          <Route path="users" element={<SamplePage title="Users"/>}/>
          <Route path="providers" element={<SamplePage title="Providers"/>}/>
          <Route path="settings" element={<SamplePage title="Settings"/>}/>
        </Routes>
      </div>
    </div>
  )
}

export default MainPage

额外优化说明

  • 使用useMatch钩子自动判断路由激活状态,无需手动维护每个SidebarItem的active属性,逻辑更可靠。
  • 添加index路由,访问/main时默认显示Dashboard页面,符合初始页面展示需求。

原代码失效原因

  • 当你在MainPage中写path="/main/dashboard"时,react-router会匹配完整路径,但App.js已将/main/*的路由控制权交给MainPage,内部子路由需基于/main使用相对路径。
  • 大写的Component是react-router v5的语法,v6中统一使用element属性,导致原Dashboard路由完全未生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:15:39