简体   繁体   中英

window.location is undefined

When I load the home page of my react-redux application I got the error

Encountered error "TypeError: Cannot read property 'search' of undefined" when prerendering App with {"location":"/","currency":"USD"}

I am getting error in following code

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;

can anyone please help me

Edit

window.location on console gives

 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

After much discussion, It's really hard to tell why assigning window.location.search.substring(1) throws an error. One way to circumvent this issue is by using a try catch clause:

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]);
    }
  }
}

To answer for the headline question title of window.location is undefined my wasted 20 minutes was because I was using the bad capitalization given here.

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

ie Window.location is wrong, window.location is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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