提问人:Amin.Qarabaqi 提问时间:7/10/2023 更新时间:7/10/2023 访问量:94
React- 添加带有 pushState 的查询参数会在参数之前添加尾部斜杠(没有 react 路由器)
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
答:
1赞
Indrasis Datta
7/10/2023
#1
若要删除 URL 中主机后面的尾部斜杠,可以使用 URL 对象的 pathname 属性来检查它是否为空。如果它为空,则可以手动构造不带尾部斜杠的 URL。
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);
评论
0赞
Amin.Qarabaqi
7/10/2023
感谢您的回复。我试过这个。更进一步,我尝试了类似.但两者都没有用!真的很奇怪!window.history.pushState(null, '', 'http://localhost:3000?someParam=someValue);
评论