React Router Dom v6嵌套路由组件不显示且无报错问题求助
问题分析与解决
你的问题出在两个关键细节上:
exact属性在react-router-dom v6中已被废弃
Routes组件下的Route默认采用精确匹配规则,写exact不仅完全无效,还可能干扰路由的匹配逻辑。用
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
相关产品推荐
相关产品推荐

