簡體   English   中英

React-Router不同路徑相同組件

[英]React-router different path same component

我有這個特殊的用例,找不到任何解決方案。 我需要對不同的路徑使用相同的組件 ,不幸的是,路徑的長度不同,如以下模式中所述

/targetpath/:targetpathId
/somepath/:somepathId/targetpath/:targetpathId
/somepath/:somepathId/someotherpath/:someotherpathId/targetpath/:targetpathId

我不想為每種情況編寫每個路由,因為它無法縮放...因此,我試圖以此方式動態編寫路徑

<Switch>
  <Route
    path={`${match.url}/targetpath/:targetpathId`}
    component={Photo}
  />
  //Other routes...
</Switch>

但是由於路線的長度可變,因此每次都無法使用

我正在使用正則表達式嘗試,但仍然沒有運氣

有人遇到過這個問題嗎?

以這種方式創建路由似乎是不明智的。 您可以簡單地定義加載相同組件的其他路由。

<Route to='/path1' component={MyComponent} />
<Route to='/path2' component={MyComponent} />

是的,必須將每個組件都寫出來很麻煩,但這要直觀得多,而且實現錯誤的可能性也較小。

好的,感謝Drusto,我已經解決了這個問題

path="(^.*)/targetpath/:targetpath"

但是總的來說,克里斯托弗·恩戈(Christopher Ngo)是對的,這是一個糟糕的路由設計,因此,我決定采用另一種方法

暫無
暫無

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

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