简体   繁体   中英

Nested route is not working as expected - React router

My code is

        <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>

Now when I am hitting history.push(/route/subroute/id) it is working

But when I try to open history.push(/route/subroute/subroute1/id) it is not opening page for me. I tried to go through the documents but all things seem to be in place. What am i missing.

+ operator at /route/subroute/:id+ makes you match /route/subroute/subsubroute1/123 for Component1 route, with a param subsubroute1/123 .

remove the + and it should work as expected.

alternatively, if you really need to use + , you can move down Component1 , and Component2 will be matched properly since react-router-dom matches the first route that matches the given path:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM