javascript - 如何使用 react-router 设置嵌套路由
问题描述
我有一个父容器:
function Home() {
render (
<Router>
<Switch>
<Route exact path="/website" component={Website} />
<Route path="/dashboard" component={Dashboard} />
<Route path="/website/web-one" component={WebOne} />
<Route path="/website/web-two" component={WebTwo} />
<Route path="/dashboard/dash-one" component={DashOne} />
<Route path="/dashboard/dash-two" component={DashTwo} />
</Switch>
</Router>
)
}
网站和仪表板都有我想根据 url 上的内容呈现的路线。这是我到目前为止所做的:
//home
function Website(){
render (
<div>
<div>Welcome to Website page</div>
<Router>
<Switch>
<Route path="/website/web-one" component={WebOne} />
<Route path="/website/web-two" component={WebTwo} />
</Switch>
</Router>
</div>
)
}
//dashboard
function Dashboard(){
render (
<div>
<div>Welcome to Dashboard page</div>
<Router>
<Switch>
<Route path="/dashboard/dash-one" component={DashOne} />
<Route path="/dashboard/dash-two" component={DashTwo} />
</Switch>
</Router>
</div>
)
}
如何确保两个嵌套路由在各自的父级上都显示得很好,并且两个父级标题保持不变。
目前,我收到此错误:
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
解决方案
几个小时后,我把它修好了,我所做的就是<Router>
从它们各自的组件中删除包装 Home 的两个子组件的标签。因为这就像在另一个路由器中拥有一个路由器。
另外,我从 Home 组件中删除了额外的 Routes 并将它们写入各自的父组件中。
现在Home
组件看起来像这样:
function Home() {
render (
<Router>
<Switch>
<Route exact path="/" component={Website} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</Router>
)
}
另外两条子路线是这样的:
//home
function Website(){
render (
<div>
<div>Welcome to Website page</div>
<Switch>
<Route path="/website/one" component={WebOne} />
<Route path="/website/two" component={WebTwo} />
</Switch>
</div>
)
}
//dashboard
function Dashboard(){
render (
<div>
<div>Welcome to Dashboard page</div>
<Switch>
<Route path="/dashboard/one" component={DashOne} />
<Route path="/dashboard/two" component={DashTwo} />
</Switch>
</div>
)
}
推荐阅读
- scala - Scala 模式匹配使用变量绑定和守卫的区别
- reactjs - 在开发中重新加载 ReactJS 页面让我空白
- java - 定制的 Tomcat JNDI 数据源
- json - 无法解码 JSON 字符串
- html - 对无序列表中的每一行使用 :not(:last-child):after 伪元素
- sql - UPDATE 语句中的 SQL 案例表达式
- html - 单击表格行 - 选择复选框
- charts - Heatbar,文本的动态位置偏移
- ansible - debian systemd:ceph-osd@x.service:在步骤 LIMITS 生成 /usr/lib/ceph/ceph-osd-prestart.sh 时失败:不允许操作
- javascript - AppModule 中导入的共享模块