最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论