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



目前我有以下代码:

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

最新更新