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

React Router Dom v6嵌套路由组件不显示且无报错问题求助

问题分析与解决

你的问题出在两个关键细节上:

  1. exact 属性在react-router-dom v6中已被废弃
    Routes组件下的Route默认采用精确匹配规则,写exact不仅完全无效,还可能干扰路由的匹配逻辑。

  2. 用location.pathname作为Route的path是错误用法
    嵌套路由时应该使用相对路径或明确的绝对路径,而非动态获取的当前location路径。比如如果Shop组件对应的父路由是/shop,内部Route的path应该设为""(相对路径,匹配/shop)或者"/shop"(绝对路径)。直接用location.pathname会让路由匹配逻辑陷入混乱,和Routes的匹配机制冲突。

修改后的代码示例

import React from 'react';
import { Route, Routes } from 'react-router-dom';
import CollectionsOverview from '../../Components/CollectionsOverview/CollectionsOverview';

const Shop = () => {
  return (
    <div className='shop-page'>
      <Routes>
        {/* 用相对路径匹配Shop组件对应的父路由 */}
        <Route path="" element={<CollectionsOverview />} />
      </Routes>
    </div>
  );
};

export default Shop;

如果想明确写绝对路径(假设父路由是/shop),也可以这样写:

<Route path="/shop" element={<CollectionsOverview />} />

修改后CollectionsOverview组件就能正常渲染了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:22:04