英文:
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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论