如何在react-router v4中的根路由上设置可选参数?

hen*_*enk 8 react-router react-router-v4

假设我有以下两条路线:

    ...
    <Route exact path="/:param1?/" component={Home}/>
    <Route path="/news" component={News}/>
    ...
Run Code Online (Sandbox Code Playgroud)

现在,当我尝试命中路由时/news,触发Home了参数的根路由param1...

我假设解决方案是在param1之前设置一个问号,/?param1这样它就可以从路由中保存,但我无法弄清楚如何在react-router v4中执行此操作

Tyl*_*nis 13

在官方文档中有一个如何执行此操作的示例.你可以在这里找到.

您需要使用Switch组件,并将/ news Route作为第一个.

<Switch>
    <Route path="/news" component={News}/>
    <Route exact path="/:param1?/" component={Home}/>
</Switch>
Run Code Online (Sandbox Code Playgroud)

Switch始终只渲染一个Route.所以在上面的例子中,如果/ news没有激活,那么/:param1将是.