redux - 如何检查道具项目是否未定义?
问题描述
我正在从 api 检索信息。在提要页面上,如果 redux 道具为空......我希望它支持“错误”消息。如果不继续。
但是,我不断收到 × TypeError: Cannot read property 'length' of undefined
props.posts.length === undefined
使用上面的方法来检查它的 undefined 是否没有阻止它遇到错误。显然,当我得到 Array length : 0 , 0 , 100 时,从 api 检索数据需要一段时间。这就是我假设我收到错误的原因。但是我怎么告诉它检查它
解决方案
您可以检查是否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
推荐阅读
- c# - 询问用户在 C# 控制台上导出文件的路径
- python - 轴的绝对定位
- rxjs - 如何使用 RxJS 创建队列
- javascript - 在 Highcharts 漏斗可视化的左侧或右侧添加标签
- sql-server - 将图像字段数据从 SQL Server 复制到 Azure Blob 存储作为 blob 块
- php - php MySQL查询两个日期时间之间的时间,但如果在范围内完成,则包括范围外的分钟数
- javascript - 使用 map() 和 filter() 从嵌套数组映射的新数组中删除未定义的元素
- wpf - WPF - 另一个程序集中的样式中的图像源
- c++ - 我有一个返回字符串向量的函数。它需要两个字符串,并返回一个字符串中缺少的字符串
- c# - 使用 GetUserASync(用户)的单元测试控制器