簡體   English   中英

react-router-dom-將參數添加到索引URL但接受頁面

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

目前,我有以下代碼:

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

“ localhost:3000”返回容器1(按預期方式)。

“ localhost:3000/123”返回容器1的不同視圖(按預期)。

但是,當我導航到“ localhost:3000 / component2 /”時,它出現在組件1的旁邊。

我的問題是如何使索引路由既接受ID又接受一個組件?

您可以嘗試將這兩條路線包裝在Switch中 ,如下所示:

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

React Router處理路由的優先級與定義它們的順序相同。 所以你的情況應該是

<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