Reputation: 191
post.Images is output from the console.
console.log("post.Images " , post.Images);
output:
[{…}]
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)
An error occurs in the code below
cover={post.Images[0] && <img alt="example" src={`http://localhost:3065:/${post.Images[0]}` } />}
but it's strange
post.Images [0] exists but undefine error is exists
I can't figure out what's causing it.
Thank you very much for letting me know
Thank you
github: https://github.com/hyunsokstar/ch6/blob/master/front/components/PostCard.js https://github.com/hyunsokstar/ch6
Upvotes: 0
Views: 48
Reputation: 2280
I think, when you call PostCard
and pass post
into this Component, the post.Images
data is undefined at the first time of render. So, in PostCard Component
, the post.Images
prop will be undefined
.
I have two ways to resolve this issue:
const PostCard = ({ post = {} }) => {
const { Images = [] } = post;
// If post.Images is undefined, default value always is an array
cover={
Images[0] && Images[0].src &&
<img alt="example" src={`http://localhost:3065/${Images[0].src}` } />
}
}
post.Images
and post.Images[0]
defined, then access to post.Images[0].src
like this:cover={
post.Images && post.Images[0] && post.Images[0].src &&
<img alt="example" src={`http://localhost:3065/${post.Images[0].src}` } />
}
Upvotes: 1
Reputation: 5473
During the initial render, Images may not be defined by that time, thus you can either create default []
in your local component or check if Images exists before accessing its value at position 0
cover={post.Images && post.Images[0] && <img alt="example" src={`http://localhost:3065:/${post.Images[0]}` } />}
Alternatively you can destructure from post
like below and reduce your code as:
const { Images = [] } = post;
and your code snippet would change like below:
cover={Images.length && <img alt="example" src={`http://localhost:3065:/${Images[0]}` } />}
Upvotes: 1