React- adding query param with pushState adds trailing slash before params (without react router)

huangapple go评论70阅读模式
英文:

React- adding query param with pushState adds trailing slash before params (without react router)

问题

我正在尝试直接操作查询参数,而不使用任何库(比如react-router,因为我现在不需要它们)。
问题是当我尝试使用以下代码添加查询参数时:

let url = new URL(window.location.toString());
url.searchParams.set('someParam', 'someValue');
window.history.pushState(null, "", url);

并且当没有路径时(我在根路径),URL 变成了 http://localhost:3000/?someParam=someValue,但我希望它像这样 http://localhost:3000?someParam=someValue,在主机后面没有斜杠。

英文:

I'm trying to manipulate my query params directly without any library (like react-router- because i don't need them now).
The problem is when i try to add query params using this codes:

let url = new URL(window.location.toString());
url.searchParams.set('someParam', 'someValue');
window.history.pushState(null, "", url);

and when there is no path (I'm in root path), the url becomes http://localhost:3000/?someParam=someValue. but i need it to be like http://localhost:3000?someParam=someValue without trailing slash after host.

答案1

得分: 1

要移除URL中主机后的斜杠,您可以使用URL对象的pathname属性来检查是否为空。如果为空,您可以手动构建不带斜杠的URL。

let url = new URL(window.location.toString());
url.searchParams.set('someParam', 'someValue');

/* 添加此条件 */
if (url.pathname === '/') {
  url = `${url.origin}${url.search}`;
}

window.history.pushState(null, '', url);
英文:

To remove the trailing slash after the host in the URL, you can use the pathname property of the URL object to check if it's empty. If it's empty, you can manually construct the URL without the trailing slash.

let url = new URL(window.location.toString());
url.searchParams.set('someParam', 'someValue');

/* Add this condition */
if (url.pathname === '/') {
  url = `${url.origin}${url.search}`;
}

window.history.pushState(null, '', url);

huangapple
  • 本文由 发表于 2023年7月10日 20:36:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/76653811.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定