window.location 未定义

window.location is undefined

当我加载我的 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]);
    }
  }
}

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

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

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