【问题标题】:Is there any way to remove equal sign at the only key parameter on the query string?有没有办法在查询字符串的唯一关键参数处删除等号?
【发布时间】:2020-10-12 11:08:24
【问题描述】:

问题

我使用无值查询字符串参数,但如果我移动到另一个页面(路由),则 url 会更改,并在无值参数中添加新的等号。页面由react js单页app编码。

例如) http://test.com:3000/abc?a=1&b=2&c&d=4 -> http://test.com:3000/abc?a=1&b=2&c=&d=4

即使我移动到另一个页面,有什么方法可以删除等号吗?

【问题讨论】:

  • 那么c的目的是什么?
  • @JahidHasan 可能是为了确认任何功能,看到一个真实的用例
  • @wantyouring 你在用 reactRouter 吗?
  • @aeXuser264 是的,我正在使用 reactRouter 正是“react-router-dom”。

标签: reactjs url-parameters query-parameters


【解决方案1】:

如果您使用URLSearchParams 将某些对象转换为查询字符串并直接传递给Link/Redirect 或其他什么。你可能想在通过之前做这样的事情,

const queryObj = {
  something: 'blah',
  confirm: '',
  else: 'features'
}

const query = new URLSearchParams(queryObj)

console.log(query.toString())
console.log(query.toString().replace(/=$|=(?=&)/g, '')) // with NoEmptyEqualSign

这里有几个query 变化的例子(保持pathname 不变),sandbox link

1:使用Link

<Link to="?confirm">No equal Sign</Link>
<Link to="?confirm=">Equal Sign with no value</Link>
<Link to="?confirm=launch">Equal Sign with value</Link>

2:使用Redirect

没有等号

<Redirect to={{ pathname: history.location.pathname, search: "?confirm" }} />

没有值的等号

<Redirect to={{ pathname: history.location.pathname, search: "?confirm=" }} />

值等号

<Redirect to={{ pathname: history.location.pathname, search: "?confirm=launch" }} />

添加额外的pathname & search 以保持pathname 不变

3: 使用useHistory

没有等号

history.push({ search: "?confirm" })

没有值的等号

history.push({ search: "?confirm=" })

值等号

history.push({ search: "?confirm=launch" })

【讨论】:

  • @wantyouring 查看答案并告诉我是否存在错误
  • 我很抱歉迟到了... "/=$|=(?=&)/g" 正则表达式完全可以解决我的问题。非常感谢!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2022-01-22
  • 2022-11-21
相关资源
最近更新 更多