首页 > 解决方案 > 如何使用 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.

标签: javascriptreactjsreact-router

解决方案


几个小时后,我把它修好了,我所做的就是<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>
      )
    }

推荐阅读