【问题标题】:react-router-dom - add param to index url but accept pagereact-router-dom - 将参数添加到索引 url 但接受页面
【发布时间】:2019-01-20 01:35:52
【问题描述】:

目前我有以下代码:

<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 但仍然接受一个组件?

【问题讨论】:

    标签: javascript reactjs path routes react-router


    【解决方案1】:

    您可以尝试将这两条路由包装在Switch 中,如下所示:

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

    【讨论】:

      【解决方案2】:

      React Router 处理具有与定义它们的顺序相同的优先级的路由。所以在你的情况下应该是

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

      【讨论】:

      • /component2/ 仍然呈现 Container1 和 Container2 吗?
      • 它需要被包裹在一个 Switch 语句中。
      猜你喜欢
      • 2021-09-15
      • 2021-12-17
      • 1970-01-01
      • 2022-09-23
      • 2019-08-03
      • 1970-01-01
      • 2021-10-01
      • 2020-07-09
      • 2022-07-10
      相关资源
      最近更新 更多