当我加载我的 react-redux 应用程序的主页时出现错误
Encountered error "TypeError: Cannot read property 'search' of undefined" when prerendering App with {"location":"/","currency":"USD"}
我在下面的代码中遇到错误
const UrlParser = {
getQueryVariable: (variable) => {
let query = window.location.search.substring(1);
let vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) === variable) {
return decodeURIComponent(pair[1]);
}
}
}
}
export default UrlParser;
谁能帮帮我
编辑
控制台上的 window.location 给出
Location {href: "http://localhost:5000/", ancestorOrigins: DOMStringList, origin: "http://localhost:5000", replace: function,
assign: function…} ancestorOrigins:DOMStringListassign:function ()hash :"" host : "localhost:5000" hostname : "localhost" href : "http://localhost:5000/" origin : "http://localhost:5000" pathname : "/" port : "5000" protocol : "http:" reload : function reload() replace : function () search : "" toString : function toString() valueOf : function valueOf() Symbol(Symbol.toPrimitive) : undefined proto : Location
最佳答案
经过多次讨论,很难说出为什么分配 window.location.search.substring(1)
会引发错误。避免此问题的一种方法是使用 try catch 子句:
getQueryVariable: (variable) => {
let query;
try {
query = window.location.search.substring(1);
} catch(e) {
// window.location.search.substring(1) throws an error, set query
// to fallback value ''
console.log(e);
query = '';
}
let vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) === variable) {
return decodeURIComponent(pair[1]);
}
}
}
关于javascript - window.location 未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44700440/