I have an avatar that shows the first letter of the user's first name. The list of user name es when the API call. If the API call not happened TypeError: Cannot read property 'charAt' of undefined error ing as there is no in put json. My react code as follows.
<Avatar
style={{ color: "#ffffff", backgroundColor: "#5e206e" }}
>
{item.user != null ? item.user.charAt(0) : "UU"}
</Avatar>
I have an avatar that shows the first letter of the user's first name. The list of user name es when the API call. If the API call not happened TypeError: Cannot read property 'charAt' of undefined error ing as there is no in put json. My react code as follows.
<Avatar
style={{ color: "#ffffff", backgroundColor: "#5e206e" }}
>
{item.user != null ? item.user.charAt(0) : "UU"}
</Avatar>
Share
Improve this question
asked Feb 18, 2021 at 18:01
DmapDmap
1991 gold badge6 silver badges21 bronze badges
1 Answer
Reset to default 2User can still be undefined and throw error. I would also check first for user.
I suggest to use Optional Chaining introduced in ES2020.
<Avatar style={{ color: "#ffffff", backgroundColor: "#5e206e" }}>
{item?.user ? item.user.charAt(0) : "UU"}
</Avatar>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745313334a4622100.html
评论列表(0条)