首页 > 解决方案 > 即使 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

标签: reactjs

解决方案


在初始渲染期间,图像可能尚未定义,因此您可以[]在本地组件中创建默认值,或者在访问其位置值之前检查图像是否存在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]}` } />}

推荐阅读