首页 > 解决方案 > 如何检查道具项目是否未定义?

问题描述

我正在从 api 检索信息。在提要页面上,如果 redux 道具为空......我希望它支持“错误”消息。如果不继续。

但是,我不断收到 × TypeError: Cannot read property 'length' of undefined

props.posts.length === undefined

使用上面的方法来检查它的 undefined 是否没有阻止它遇到错误。显然,当我得到 Array length : 0 , 0 , 100 时,从 api 检索数据需要一段时间。这就是我假设我收到错误的原因。但是我怎么告诉它检查它

标签: reduxreact-redux

解决方案


您可以检查是否props.posts已定义(或真实):

if(!props.posts){
  // props.posts is falsy here, which won't be the case when it's an array
}

其他选项包括:

帮助执行此检查的可选链接。它有很好的浏览器支持,create react app 默认支持。

props.posts?.length === undefined

逻辑运算符短路:即如果props.posts为假,!props.posts则为真,它永远不会到达运算符的右侧||

!props.posts || props.posts.length === undefined

推荐阅读