reactjs - 即使 post.Images [0] 存在,为什么会出现问题?TypeError:无法读取未定义的属性“0”
问题描述
post.Images 从控制台输出。
console.log("post.Images " , post.Images);
输出:
[{…}]
0: {id: 5, src: "dokyo11573054801107.png", createdAt: "2019-11-06T15:40:02.000Z", updatedAt: "2019-11-06T15:40:02.000Z", PostId: 14}
length: 1
__proto__: Array(0)
下面的代码出现错误
cover={post.Images[0] && <img alt="example" src={`http://localhost:3065:/${post.Images[0]}` } />}
但这很奇怪
post.Images [0] 存在但未定义错误存在
我不知道是什么原因造成的。
非常感谢你让我知道
谢谢
github: https ://github.com/hyunsokstar/ch6/blob/master/front/components/PostCard.js https://github.com/hyunsokstar/ch6
解决方案
在初始渲染期间,图像可能尚未定义,因此您可以[]
在本地组件中创建默认值,或者在访问其位置值之前检查图像是否存在0
cover={post.Images && post.Images[0] && <img alt="example" src={`http://localhost:3065:/${post.Images[0]}` } />}
或者,您可以从下面解构post
并将您的代码减少为:
const { Images = [] } = post;
并且您的代码段将更改如下:
cover={Images.length && <img alt="example" src={`http://localhost:3065:/${Images[0]}` } />}
推荐阅读
- ios - 使用 handleWatchKitExtensionRequest
- php - Wordpress - 获取帖子中当前使用的附件图像
- java - 我面临 java.lang.StringIndexOutOfBoundsException:
- java - 在 Hibernate 中使用 SEQUENCE 时导致唯一约束违规的原因是什么?
- expression - 如何在不简化的情况下将字符串转换为 Sympy 表达式?
- ruby-on-rails - Rails 断言 - 最佳实践?
- javascript - 在 jquery $.when(ajax).done(function(){do sth} 中,我怎样才能两次回调到同一个回调函数?
- amazon-web-services - Docker 拉取错误 AWS ECR“未经授权:需要身份验证”
- azure - 比较 Azure SQL 和 Cosmos DB 之间的读取性能的好方法是什么?
- ios - 如何在 TableView 单元格之间进行分隔