简体   繁体   中英

react-router-dom - add param to index url but accept page

Currently I have the following code:

<Router history={history}>
  <div>
    <Route exact path="/:id?" component={Container1} />
    <Route path="/component2/ component={Container2} />
  </div>
</Router>

"localhost:3000" returns Container 1 (as expected).

"localhost:3000/123" returns a different view of Container 1 (as expected).

However when I navigate to "localhost:3000/component2/" it appears along side Component 1.

My question is how can I make the index route take both an id but still accept a component?

You can try to wrap these two routes in Switch , like this:

<Router history={history}>
  <div>
    <Switch>
      <Route path="/component2/" component={Container2} />
      <Route exact path="/:id?" component={Container1} />
    </Switch>
  </div>
</Router>

React Router handles the routes with the same priorities as in which order did they get defined. So in your case it should be

<Router history={history}>
  <div>
    <Route path="/component2/ component={Container2} />
    <Route exact path="/:id?" component={Container1} />
  </div>
</Router>

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