如果
url本身已经包含参数(例如url = "/path?key1=value1"),直接拼接?token=会覆盖原有参数或导致格式错误。以下是 安全拼接 URL 参数 方法:
方法 1:使用 URLSearchParams(现代浏览器推荐)
const urlWithParams = new URL(url, window.location.origin);// 添加/覆盖 token 参数
urlWithParams.searchParams.set('token', token_706);// 生成完整 URL
const finalUrl = urlWithParams.pathname + urlWithParams.search;dispatch(routerRedux.push(finalUrl));
示例:
输入
url = "/path?key1=value1"→ 输出/path?key1=value1&token=xxx输入
url = "/path"→ 输出/path?token=xxx
方法 2:手动处理字符串(兼容旧环境)
const hasExistingParams = url.includes('?');
const separator = hasExistingParams ? '&' : '?';
const finalUrl = `${url}${separator}token=${encodeURIComponent(token_706)}`;dispatch(routerRedux.push(finalUrl));
关键点:
使用
encodeURIComponent避免特殊字符(如&,=)破坏 URL 结构。自动检测原 URL 是否已有参数,选择
?或&连接符。
