反应路由器可以有一个带有多个选项参数的路由,其中​​(例如)两者都是必需的,或者 none

Can react router have a route with multiple option parameters where (e.g.) both are required, or none

使用 react-router-dom 我有这样的路线:

<Route path='/:year?/:month?' component={ThingUsingYearAndMonth} />

但我真的希望年份和月份都存在(例如 /2018/Dec/2017/Jan)或两者都不存在。 IE。只是 /2018 不匹配

我可能会使用两条路线来处理这个问题——一条用于同时提供两者,另一条用于两者均未提供:

<Route path='/:year/:month' component={ThingUsingYearAndMonth} />
<Route path='/' exact component={ThingUsingYearAndMonth} />

尝试使用正则表达式提供显式参数:

<Route path='/:year(\d{4})?/:month([A-Za-z]+)?' component={ThingUsingYearAndMonth} />

我认为 react-router-dom 没有提供任何机制来验证路由参数。您最好创建自己的高阶组件并验证其中的路由参数。或者您可以使用正则表达式在路由本身中验证您的参数。