【问题标题】:ReactJS Router DOM. Dynamic routes with regexReactJS 路由器 DOM。使用正则表达式的动态路由
【发布时间】:2018-03-17 08:05:58
【问题描述】:

我目前正在玩一些 React Router Dom 并且我在质疑是否有可能拥有一些动态路由。

我知道我可以通过以下方式进行一些动态路由:

<Route path="/component/:param" component={Component} />

我想要的,如下:

例如我有一个过滤器页面。在此页面上,我有以下过滤器:

面积

  • 佛罗里达
  • 迈阿密
  • 纽约

兴趣

  • 网络开发
  • 社交媒体
  • 营销

等级

  • 初学者
  • 中级
  • 高级

等等

我的 URL 应该是,当我选择 Florida 作为区域,Webdevelopment 和 Social media 作为兴趣,Beginner 作为级别时,如下

/component/filter/areas/florida/interests/webdevelopment;social-media/levels/beginner

上面很简单:

<Route path="/component/filter/areas/:areas/interests/:interests/levels/:levels" component={Component} />

但是,也有可能是这样的:

/component/filter/interests/webdevelopment;social-media

/component/filter/areas/new-york

/component/filter/interests/webdevelopment;social-media/areas/new-york

是否可以有 1 个(或 2 个)路由,其中​​所有项目的 /component 路径和过滤器的路径,而不必为其定义所有不同的路径?因为例如,当我有 50 个过滤器时,我真的不希望只有我的过滤器有 1000 多行。

提前感谢您的回答!

【问题讨论】:

  • 这个 URL 模式很奇怪。显然areainterestslevels 应该在查询字符串中。例如:"/component/filter?area=${encodeURLComponent(areas)}&amp;interests=${encodeURLComponent(interests)}&amp;levels=${encodeURLComponent(levels)}"
  • 你能告诉我为什么它很奇怪吗?在我看来,它对搜索引擎非常友好,我可以在结果上方创建每个过滤器的描述。 - 在纽约寻找网络开发会议 - 在佛罗里达等地寻找社交媒体会议。
  • 因为您拥有的所有过滤条件都处于同一级别(没有父子关系)。如果从查询字符串中提取值,则顺序和缺失值无关紧要。但是在您的网址中,当areasinterests 缺失时,您需要提供单独的路线。
  • 只使用本地存储

标签: javascript reactjs react-router-v4 react-router-dom


【解决方案1】:

如果您有一些可选的过滤器,那么您可以定义类似的路由

<Route path="/component/filter(/areas/:areas)?(/interests/:interests)?(/levels/:levels)?" component={Component} />

但是对于大量过滤器来说,将过滤器作为 URL 参数确实没有意义,而您应该使用类似的查询参数

你的网址可能是这样的

`?areas=new-york&interests=webdevelopment,socialmedia&levels=1`

然后你可以在组件中解析它。

附:上面的url应该是urlencoded

how you would intergrate and detect change inquery params with react-router-v4上查看这个答案

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 2019-03-24
    • 2011-11-05
    • 2019-01-28
    • 1970-01-01
    • 2018-12-20
    • 2020-10-10
    • 2019-01-01
    • 2014-04-14
    相关资源
    最近更新 更多