簡體   English   中英

可以使路由器的路由帶有多個選項參數,其中(例如)兩個都需要,或者都不是

[英]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 ),或者都不存在。 即只是/ 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沒有提供任何機制來驗證路由參數。 您最好創建自己的高階組件並在其中驗證路徑參數。 或者,您可以使用正則表達式來驗證路線本身中的參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM