简体   繁体   English

React-Router不同路径相同组件

[英]React-router different path same component

I have this particular use case and I cannot find any solution. 我有这个特殊的用例,找不到任何解决方案。 I need to use the same component for different paths , unfortunately the paths have different lengths like described in the pattern below 我需要对不同的路径使用相同的组件 ,不幸的是,路径的长度不同,如以下模式中所述

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

I don't want to write each route for each case because it does not scale... So I am trying to write the path dynamically in this way 我不想为每种情况编写每个路由,因为它无法缩放...因此,我试图以此方式动态编写路径

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

But because the routes have variable lengths this does not work every time 但是由于路线的长度可变,因此每次都无法使用

I am trying with Regex but still no luck 我正在使用正则表达式尝试,但仍然没有运气

Anyone that has encountered this problem? 有人遇到过这个问题吗?

It seems unwise to create routes in the this manner. 以这种方式创建路由似乎是不明智的。 You can simply define a different route that loads the same component. 您可以简单地定义加载相同组件的其他路由。

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

Yes, it's a pain having to write each component out, but it's far more intuitive, and you're less likely to implement a bug. 是的,必须将每个组件都写出来很麻烦,但这要直观得多,而且实现错误的可能性也较小。

Ok, I have solved like this, thanks to Drusto 好的,感谢Drusto,我已经解决了这个问题

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

But in general Christopher Ngo was right that is a bad routing design and therefore I have decided to get another approach 但是总的来说,克里斯托弗·恩戈(Christopher Ngo)是对的,这是一个糟糕的路由设计,因此,我决定采用另一种方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM