我正在使用ReactJS访问API。当组件访问由API提供的对象中可能为'undefined'的属性时,如何防止React组件崩溃?
错误示例:
TypeError: Cannot read property 'items' of undefined
我正在使用ReactJS访问API。当组件访问由API提供的对象中可能为'undefined'的属性时,如何防止React组件崩溃?
错误示例:
TypeError: Cannot read property 'items' of undefined
看起来你正在尝试访问变量x
的属性items
。
如果x
是undefined
,那么调用x.items
将会导致你提到的错误。
���行一个简单的:
if (x) {
// CODE here
}
或者if (x && x.items) { // ensures both x and x.items are not undefined
// CODE here
}
编辑:
现在你可以使用可选链操作符,它看起来非常好:
if (x?.items)
if(typeof x !=='undefined' && typeof x.item !=='undefined'){
}
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>
这篇文章讨论了一些在React应用中处理错误的策略。
但在你的情况下,我认为使用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;
}
我假设你只是在处理一个特定的麻烦的React组件。如果你想处理类似类型的错误,我建议你使用上面博客文章中提到的ReactTryCatchBatchingStrategy
。
检查这类问题的最佳方法是在Google控制台中运行测试代码。例如,对于空值检查,可以简单地检查if(!x)
或if(x==undefined)
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // detailed address is unknown
}
};
let customerCity = customer.details?.address?.city;
你可以简单地使用条件
if (var){
// Statement
} else {
// Statement
}