2017-06-22 107 views
1

當我打開我的反應,終極版應用程序的主頁,我得到了錯誤window.location的是未定義

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

+0

請詳細說明問題;你在哪一行遇到錯誤?哪個輸入? – pinturic

+0

@pinturic let query = window.location.search.substring(1); – Anish

+0

https://stackoverflow.com/a/26803253/6294260?zh_CN如果它對你有幫助,請檢查此鏈接。 –

回答

2

經過大量討論,很難說出爲什麼分配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]); 
    } 
    } 
} 
+0

我不知道爲什麼,但這解決了問題!!,你能解釋我怎麼... – Anish

+0

try catch語句防止錯誤被拋出,因爲它知道你期望你在catch語句中處理它:https:// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch –