在ReactJS中处理空值的最佳方法? [英] Best way to handle null values in ReactJS?

查看:101
本文介绍了在ReactJS中处理空值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ReactJS访问API.在React组件访问API提供的对象中可能是未定义"的属性时,阻止React组件崩溃的最佳方法是什么?

一个错误的例子是:

TypeError:无法读取未定义的属性"items"

解决方案

您似乎正在尝试访问变量 x 的属性 items .

如果 x undefined ,那么调用 x.items 将给您提到的错误.

做一个简单的事情:

  if(x){//这里的代码} 

  if(x&& x.items){//确保x和x.items都未定义//这里的代码} 

您现在可以使用可选链接,看起来很甜:

  if(x?.items) 

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'?

An example of an error is:

TypeError: Cannot read property 'items' of undefined

解决方案

It looks like you're trying to access the property items of a variable x.

And if x is undefined, then calling x.items will give you the error you mentioned.

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:

if (x?.items)

这篇关于在ReactJS中处理空值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆