Javascript 在 ReactJS 中处理空值的最佳方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44531204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best way to handle null values in ReactJS?
提问by Nathan Horrigan
I'm accessing an API with ReactJS. What is the best way to stop React Component crashing when it's accessing a property in the object provided by the API that may be 'undefined'?
我正在使用 ReactJS 访问 API。当 React Component 访问 API 提供的对象中可能“未定义”的属性时,阻止它崩溃的最佳方法是什么?
An example of an error is:
错误的一个例子是:
TypeError: Cannot read property 'items' of undefined
类型错误:无法读取未定义的属性“items”
回答by Kenny Meyer
It looks like you're trying to access the property itemsof a variable x.
看起来您正在尝试访问items变量的属性x。
And if xis undefined, then calling x.itemswill give you the error you mentioned.
如果x是undefined,那么调用x.items会给你你提到的错误。
Doing a simple:
做一个简单的:
if (x) {
// CODE here
}
or
或者
if (x && x.items) { // ensures both x and x.items are not undefined
// CODE here
}
EDIT:
编辑:
You can now use Optional Chaining, which looks sweet:
您现在可以使用Optional Chaining,它看起来不错:
if (x?.items)
回答by Rajat Gupta
- In simple function you do it simply by if statement.
- 在简单函数中,您只需通过 if 语句即可完成。
if(typeof x !=='undefined' && typeof x.item !=='undefined'){
}
- in JSX you do it in this way.
- 在 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>
回答by Mμ.
This posttalks about a few error handling strategy in your react app.
这篇文章讨论了 React 应用程序中的一些错误处理策略。
But in your case, I think using try-catch clause would be the most convenient.
但是在您的情况下,我认为使用 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;
}
I assume that you are using this only for one particular pesky react component. If you want to handle similar type of error, I suggest you use ReactTryCatchBatchingStrategyin the blog post above.
我假设您仅将它用于一个特定的讨厌的反应组件。如果您想处理类似类型的错误,我建议您ReactTryCatchBatchingStrategy在上面的博客文章中使用。
回答by keshav goswami
Best way to check for any such issue is to run your test code in google's console.
Like for a null check, one can simply check
if(!x)or
if(x==undefined)
检查任何此类问题的最佳方法是在 google 的控制台中运行您的测试代码。就像空检查一样,可以简单地检查
if(!x)或
if(x==undefined)
回答by Sunny Sultan
The optional chaining operator provides a way to simplify accessing values through connected objects when it's possible that a reference or function may be undefined or null.
当引用或函数可能未定义或为空时,可选链运算符提供了一种简化通过连接对象访问值的方法。
let customer = {
name: "Carl",
details: {
age: 82,
location: "Paradise Falls" // detailed address is unknown
}
};
let customerCity = customer.details?.address?.city;

