2017-06-13 199 views

回答

1

它看起來像你試圖訪問的變量x財產items

如果xundefined,那麼調用x.items會給你提到的錯誤。

做一個簡單:

if (x) { 
    // CODE here 
} 

if (x && x.items) { // ensures both x and x.items are not undefined 
    // CODE here 
} 
1
  • 在簡單的功能,你這樣做只是通過if語句。

if(typeOf x !=='undefined' && typeOf x.item !=='undefined'){ 
 

 
}

  • 在JSX你做這樣。

render(){ 
 
return(
 
      <div> 
 
      (typeOf x !=='undefined' && typeOf x.item !=='undefined)? 
 
       <div>success</div>:   
 
       <div>fail</div> 
 
      </div> 
 
     ) 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

+0

我已經這樣做了,但我仍然收到錯誤 –

+0

假設x是一個對象並且有項目。所以首先檢查x是否未定義或爲空。然後檢查x.items。檢查我的答案。 –

+0

操作順序問題,在if語句首先你必須檢查對象的屬性。 –

0

This post約了幾個錯誤處理策略會談,你的反應程序。

但在你的情況,我認爲使用try-catch子句將是最方便的。

let results; 
 
const resultsFallback = { items: [] }; 
 
try { 
 
    // assign results to res 
 
    // res would be an object that you get from API call 
 
    results = res.items; 
 
    // do stuff with items here 
 
    res.items.map(e => { 
 
    // do some stuff with elements in items property 
 
    }) 
 
} catch(e) { 
 
    // something wrong when getting results, set 
 
    // results to a fallback object. 
 
    results = resultsFallback; 
 
}

我假設你正在使用這個只爲一個特定的討厭反應成分。如果您想處理類似的錯誤,我建議您在上面的博客文章中使用ReactTryCatchBatchingStrategy

相關問題