简体   繁体   English

react-router-dom-将参数添加到索引URL但接受页面

[英]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”返回容器1(按预期方式)。

"localhost:3000/123" returns a different view of Container 1 (as expected). “ localhost:3000/123”返回容器1的不同视图(按预期)。

However when I navigate to "localhost:3000/component2/" it appears along side Component 1. 但是,当我导航到“ localhost:3000 / component2 /”时,它出现在组件1的旁边。

My question is how can I make the index route take both an id but still accept a component? 我的问题是如何使索引路由既接受ID又接受一个组件?

You can try to wrap these two routes in Switch , like this: 您可以尝试将这两条路线包装在Switch中 ,如下所示:

<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. React Router处理路由的优先级与定义它们的顺序相同。 So in your case it should be 所以你的情况应该是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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