首页 > 解决方案 > 嵌套路由未按预期工作 - React 路由器

问题描述

我的代码是

        <Switch>
          <Route path='/' exact render={() => <Redirect to='/route' />} />
          <Route path='/route/' exact render={() => <Component />} />
          <Route path='/route/subroute/:id+' exact render={() => <Component1/>} />
          <Route path='/route/subroute/subsubroute1/:id+' exact render={() => <Component2 />} />
          <Route path='/route/subroute/subsubroute2/:id+' exact render={() => <Component3 />} />
          <Route path='/route/:subroute+' exact render={() => <Component4 />} />
          <Route render={() => <Redirect to='/notfound' />} />
        </Switch>

现在当我击中history.push(/route/subroute/id)它时它正在工作

但是当我尝试打开history.push(/route/subroute/subroute1/id)它时,它并没有为我打开页面。我试图浏览文件,但一切似乎都已到位。我错过了什么。

标签: javascriptreactjsreact-routerreact-router-dom

解决方案


+运算符 at使/route/subroute/:id+您匹配路线,并带有 param 。/route/subroute/subsubroute1/123Component1subsubroute1/123

删除+它,它应该可以按预期工作。

或者,如果您确实需要使用+,则可以向下移动Component1,并且Component2将正确匹配,因为react-router-dom匹配与给定路径匹配的第一个路由:

<Switch>
  <Route path='/' exact render={() => <Redirect to='/route' />} />
  <Route path='/route/' exact render={() => <Component />} />
  <Route path='/route/subroute/subsubroute1/:id+' exact render={() => <Component2 />} />
  <Route path='/route/subroute/subsubroute2/:id+' exact render={() => <Component3 />} />
  <Route path='/route/subroute/:id+' exact render={() => <Component1/>} />
  <Route path='/route/:subroute+' exact render={() => <Component4 />} />
  <Route render={() => <Redirect to='/notfound' />} />
</Switch>

推荐阅读