React无React Router时pushState加查询参数出现多余斜杠问题
去除根路径URL中主机后的多余斜杠
当在根路径(如http://localhost:3000/)下使用原生JS操作查询参数时,执行以下代码后:
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。
解决方案
方法一:字符串替换修正URL
针对根路径的情况,用字符串替换去掉多余斜杠:
const url = new URL(window.location.toString()); url.searchParams.set('someParam', 'someValue'); let targetUrl = url.toString(); // 仅根路径时替换"/?"为"?" if (url.pathname === '/') { targetUrl = targetUrl.replace('/?', '?'); } window.history.pushState(null, "", targetUrl);
方法二:手动拼接URL各部分
直接基于协议、主机和查询参数构造目标URL,跳过默认的根路径斜杠:
const { protocol, host, searchParams } = new URL(window.location); searchParams.set('someParam', 'someValue'); // 有查询参数时才拼接"?"开头的字符串 const queryString = searchParams.toString() ? `?${searchParams.toString()}` : ''; // 直接拼接协议、主机和查询参数,无需根路径斜杠 const targetUrl = `${protocol}//${host}${queryString}`; window.history.pushState(null, "", targetUrl);
两种方法都能实现需求:方法一适合快速修改现有代码,方法二更可控,避免依赖URL对象的默认路径处理逻辑。
内容的提问来源于stack exchange,提问作者Amin.Qarabaqi
相关产品推荐
相关产品推荐

