在 React Router v5 中,写子路由,父级路由如果加了exact属性,就显示不了子组件

在 React Router v5 中,当你在父级路由上使用 exact 属性时,它意味着该路由只有在其 path 完全匹配当前 URL 时才会被激活。这意味着,如果父级路由精确匹配了,React Router 就不会继续向下查找子路由,因为 exact 限制了匹配范围。

例如,假设你有以下路由配置:

复制代码
<Route exact path="/parent" component={ParentComponent}>
  <Route path="/parent/child" component={ChildComponent} />
</Route>

在这个例子中,如果你访问 /parent,因为父级路由设置了 exact,它将匹配并仅渲染 ParentComponent。即使存在一个子路由 /parent/child,由于父级路由已经精确匹配,React Router 不会继续尝试匹配子路由,因此 ChildComponent 不会被渲染。

如果你希望同时能够访问父级和子级组件,应该移除父级路由上的 exact 属性,让路由系统有机会继续匹配子路由:

复制代码
<Route path="/parent">
  <Route path="/parent/child" component={ChildComponent} />
</Route>

这样配置后,访问 /parent 会渲染 ParentComponent,而访问 /parent/child 则会同时渲染 ParentComponent(作为容器)和 ChildComponent。如果没有其他路由与 /parent 完全匹配,就不需要 exact,因为默认情况下 Route 并不要求完全匹配。

相关推荐
小码哥_常几秒前
Room 3.0:移动端持久化的“重生”变革
前端
Beginner x_u34 分钟前
链表专题:JS 实现原理与高频算法题总结
javascript·算法·链表
Front思41 分钟前
前端的.hbs
前端
我叫汪枫1 小时前
在后台管理系统中,如何递归和选择保留的思路来过滤菜单
开发语言·javascript·node.js·ecmascript
_.Switch1 小时前
东方财富股票数据JS逆向:secids字段和AES加密实战
开发语言·前端·javascript·网络·爬虫·python·ecmascript
软件技术NINI1 小时前
webkit简介及工作流程
开发语言·前端·javascript·udp·ecmascript·webkit·yarn
Brendan_0011 小时前
JavaScript的Stomp.over
开发语言·javascript·ecmascript
普通网友1 小时前
ES6模块化、Promise、async、await、EventLoop、API接口案例_export function 与 await
前端·ecmascript·es6
念2341 小时前
f5 shape分析
开发语言·javascript·ecmascript
難釋懷1 小时前
Vue混入
前端·javascript·vue.js