简体   繁体   English

使用react-router定制动态路由

[英]Custom dynamic routes using react-router

There is little unconventional routes requirement for a project i am working on. 我正在开展的项目几乎没有非常规路线要求。 The route has following structure /<--name-->-abc-xyz-<--id--> where name and id are dynamic. 该路由具有以下结构/<--name-->-abc-xyz-<--id-->其中name和id是动态的。 Now i want to match this route using react router. 现在我想使用反应路由器匹配此路由。 So i did the following 所以我做了以下事情

<Route path='/:name-abc-xyz-:id' component={View} />

This fails for the cases where name name is of this form def-abc-xyz-*. 对于名称名称为def-abc-xyz- *的情况,这会失败。

How to fix this such that i get value of name and id in View component directly. 如何修复此问题,以便直接在View组件中获取name和id的值。

I have a workaround where i do <Route path='/:dynamicId' component={View} /> 我有一个解决方法,我做<Route path='/:dynamicId' component={View} />

and now i parse dynamicId and take out name and id from it in my View compoenent. 现在我解析dynamicId并从我的View组件中取出它的名称和id。 Is there a way to achieve the following without parsing ? 有没有办法在不解析的情况下实现以下目的?

Standard routing 标准路由

The standard way how this is managed in V4 is to provide a route in config as: 在V4中管理它的标准方法是在config中提供以下路由:

/:name/abc-xyz/:id

If you are not constrained by another parser to use the above dashed-schema this solution will fit your needs. 如果您不受另一个解析器约束使用上述虚线架构,则此解决方案将满足您的需求。

Ref: https://github.com/reacttraining/react-router/tree/master/packages/react-router-config#route-configuration-shape 参考: https//github.com/reacttraining/react-router/tree/master/packages/react-router-config#route-configuration-shape

if you have conflict with static routes place the dynamic route last in route scaffolding 如果您与静态路由冲突,请将动态路由放在路径脚手架中

Ref: https://tylermcginnis.com/react-router-ambiguous-matches/ 参考: https//tylermcginnis.com/react-router-ambiguous-matches/

Custom route formats 自定义路由格式

Additionaly, notice 另外,请注意

React Router uses path-to-regexp for its route matching. React Router使用path-to-regexp进行路由匹配。

This means that if you provide a route in this format: 这意味着如果您以这种格式提供路线:

/:name(\w+-)?abc-xyz(\w+-)?:id

This will work too while comparing (IE) 比较(IE)时这也会起作用

def-abc-xyz-12

Screenshot from route tester 路线测试仪截图

在此输入图像描述 Ref: https://github.com/ReactTraining/react-router/issues/5536#issuecomment-330548834 参考: https//github.com/ReactTraining/react-router/issues/5536#issuecomment-330548834

Route tester: https://pshrmn.github.io/route-tester/#/def-abc-xyz-12 路线测试仪: https//pshrmn.github.io/route-tester/#/def-abc-xyz-12

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

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