2017-04-18 97 views
0

我路由的頁面保持相同的組件結構,但其內容基於URL略有變化。當這個區域設置了我的路我目前使用的結構如下:使用React-Router路由OR路徑

<Route path="/:focusPath/read/agree" component={ViewerLayout} /> 
<Route path="/:focusPath/read/neutral" component={ViewerLayout} /> 
<Route path="/:focusPath/read/disagree" component={ViewerLayout} /> 
<Route path="/:focusPath/speak/agree" component={ViewerLayout} /> 
<Route path="/:focusPath/speak/neutral" component={ViewerLayout} /> 
<Route path="/:focusPath/speak/disagree" component={ViewerLayout} /> 

然而,這似乎重複和過於複雜。儘管它按原樣工作,但是我可以通過重塑它來完成這樣的事情嗎?

<Route path={"/:focusPath"+("/read"||"/speak")+("/agree"||"/neutral"||"/disagree")} component={ViewerLayout} /> 

我意識到語法都是錯誤的,但也許是簡化了它使它工作的6行的東西?

回答

2

這不推薦,但它應該適用於您的用例。你可以傳遞一個正則表達式到path。這裏有一個片段可以幫你找到正確的想法。

<Route path="/:focusPath/read/(/agree|neutral|disagree/)" component={ViewerLayout} /> 

我是垃圾在正則表達式,所以可能不會像現在這樣工作,但你明白了。

+0

甜!謝謝,我沒有意識到我可以使用正則表達式! 如果你想要一些練習,或者只是想嘗試一些工作,[RegEx101](https://regex101.com/)是在正則表達式中更好的工具。 ;) –

+0

真棒我會檢查出來。謝謝! –