在ReactJS中处理未定义的值的最佳方法是什么?

22

我正在使用ReactJS访问API。当组件访问由API提供的对象中可能为'undefined'的属性时,如何防止React组件崩溃?

错误示例:

TypeError: Cannot read property 'items' of undefined

6个回答

36

看起来你正在尝试访问变量x的属性items

如果xundefined,那么调用x.items将会导致你提到的错误。

���行一个简单的:

if (x) {
  // CODE here
}
或者
if (x && x.items) { // ensures both x and x.items are not undefined
  // CODE here
}

编辑:

现在你可以使用可选链操作符,它看起来非常好:

if (x?.items)

问题是针对null的。这会产生不同于undefined的结果。在React中,如果(myvalue.doesnotExist)会报错null不是一个对象(评估'myvalue.doesnotExist')。实际上标题是针对null的,但代码是针对undefined的,所以你在undefined方面是正确的。我的道歉。 - FabricioG

4
  • 在简单的函数中,您可以通过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>


假设x是一个对象并且有一个项目。首先检查x是否未定义或为空。然后检查x.items。请检查我的答案。 - Rajat Gupta
操作的顺序很重要,在if语句中,首先必须检查对象,然后再检查其属性。 - Rajat Gupta

2

这篇文章讨论了一些在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


1

检查这类问题的最佳方法是在Google控制台中运行测试代码。例如,对于空值检查,可以简单地检查if(!x)if(x==undefined)


1
可选链运算符提供了一种简化通过连接对象访问值的方式,当引用或函数可能未定义或为空时使用。
let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // detailed address is unknown
  }
};
let customerCity = customer.details?.address?.city;

0

你可以简单地使用条件

if (var){
// Statement
} else {
// Statement
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接