繁体   English   中英

window.location 未定义

[英]window.location is undefined

当我加载 react-redux 应用程序的主页时,出现错误

使用 {"location":"/","currency":"USD"} 预渲染应用程序时遇到错误“TypeError:无法读取未定义的属性‘搜索’”

我在以下代码中遇到错误

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,

分配:函数...}祖先起源:DOMStringListassign:函数()哈希:“”主机:“本地主机:5000”主机名:“本地主机”href:“ http://localhost:5000/ ”原点:“ http://localhost:5000 " 路径名: "/" 端口: "5000" 协议: "http:" reload : function reload() 替换: function () 搜索: "" toString : function toString() valueOf : function valueOf() Symbol(Symbol.toPrimitive) :未定义的原型:位置

经过多次讨论,很难说为什么分配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]);
    }
  }
}

要回答window.location的标题问题未定义,我浪费了 20 分钟是因为我使用了此处给出的错误大写。

https://developer.mozilla.org/en-US/docs/Web/API/Window/location

Window.location是错误的, window.location是正确的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM