【发布时间】:2017-11-15 19:19:08
【问题描述】:
我正在使用 ReactJS 访问 API。当 React 组件访问 API 提供的对象中可能“未定义”的属性时,阻止 React 组件崩溃的最佳方法是什么?
错误示例如下:
TypeError:无法读取未定义的属性“项目”
【问题讨论】:
标签: javascript reactjs javascript-objects
我正在使用 ReactJS 访问 API。当 React 组件访问 API 提供的对象中可能“未定义”的属性时,阻止 React 组件崩溃的最佳方法是什么?
错误示例如下:
TypeError:无法读取未定义的属性“项目”
【问题讨论】:
标签: javascript reactjs javascript-objects
您似乎正在尝试访问变量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
}
编辑:
你现在可以使用Optional Chaining,看起来很甜:
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>
【讨论】:
This post 讨论了你的 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;
}
我假设您仅将它用于一个特定的讨厌的反应组件。如果你想处理类似类型的错误,我建议你在上面的博文中使用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;
【讨论】: