【问题标题】:Remove '%20' from URL - React-Router从 URL 中删除 '%20' - React-Router
【发布时间】:2018-09-16 15:23:27
【问题描述】:

我在使用 react 时遇到了一个问题,尽管是美学问题而不是功能问题。

我正在从名称 API 生成 react-routes。该路线工作正常,但由于名称有空格,它们在 url 中显示为:example.com/lookup/David%20Attenborough

示例:<Link to='{/lookup/' + props.data.name}>{props.data.name}</Link>

有没有一种聪明的方法可以删除空格:example.com/lookup/DavidAttenborough 甚至使用+- 来替换空格,而不会失去react-router 的结构完整性。

【问题讨论】:

  • 你可以这样做:props.data.name.split(' ').join('');或者使用正则表达式
  • 你可以在 props.data.name 上使用 .split(' ').join('-'),但我不确定你的路由器是否会损坏
  • @floor 你也打败了我吧
  • 这叫做蛞蝓,你可以用slugifyothers来做到这一点。 失去 react-router 的结构完整性是什么意思?

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


【解决方案1】:

实际上,+ 作为路径中空格的编码无效,仅在查询字符串中有效。见When to encode space to plus (+) or %20?https://github.com/ReactTraining/react-router/issues/2407

你不能按照你的要求去做

【讨论】:

    【解决方案2】:

    您可以使用正则表达式在网址中添加(- 或 +) 例子

    let name = props.data.name;
    name = name.replace(/\s+/g, '-');
    const url = `/lookup/${name}
    
    <Link to={url}>{props.data.name}</Link>
    

    您可以添加 + 或 -

    【讨论】:

    • 在某些浏览器上,这只会改变 %20 的第一次出现,尝试添加一个循环 (while(name.contains("%20") ... replace) 或测试以使用 replaceAll如果支持
    猜你喜欢
    • 2022-09-22
    • 2016-05-12
    • 2016-11-04
    • 2021-10-16
    • 1970-01-01
    • 2016-04-08
    • 2015-10-26
    • 1970-01-01
    • 2017-01-16
    相关资源
    最近更新 更多