有什么方法可以删除查询字符串中唯一关键参数的等号吗?

Is there any way to remove equal sign at the only key parameter on the query string?

问题

我使用了无值查询字符串参数,但是如果我移动到另一个页面(路由),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

有什么方法可以在我移动到另一个页面时去掉等号吗?

如果你使用 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" })