javascript - How to avoid TypeError: Cannot read property 'charAt' of undefined when the json input is not avail

I have an avatar that shows the first letter of the user's first name. The list of user name es wh

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
Add a ment  | 

1 Answer 1

Reset to default 2

User 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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信