问题: 路由跳转时, 页面发出了两次一模一样的网络请求, 但是当前页刷新时, 仅发出一次请求.
问题条件说明: 在跳转路由上带参数, 且参数中包含中文
问题分析: 浏览器对中文参数进行转码导致组件加载两次
解决方案: 在传递参数时, 对参数用encodeURI进行转码, 接收参数时用decodeURI解码
// 获取props.location.search中的参数值
const getQuery = (search) => {
let obj = {};
if (search) {
let params = search.split('?')[1].split('&');
for (let i = 0; i < params.length; i++) {
let param = params[i].split('=');
obj[param[0]] = decodeURI(param[1]);
}
}
return obj;
};
// 把参数对象转换为search字符串
const getSearch = (obj) => {
let str = '';
if (obj && typeof obj === 'object') {
str = '?';
for (let i in obj) {
if (obj[i]) {
str = str + i + '=' + encodeURI(obj[i]) + '&';
}
}
str = str.substring(0, str.length - 1);
}
return str;
}
// 传参跳转
let storageData = { type: 'business', typeName: '帖子', typeId: '123123' };
history.push('/DC/logDetail/infoResource' + getSearch(storageData));
// 跳转到页解析参数(hook)
let data = getQuery(props.location.search);
let { type, typeName, typeId } = data;