Javascript 如何避免类型错误:无法读取属性';查拉特';当json输入不可用时的未定义值?
我有一个显示用户名字第一个字母的化身。API调用时会出现用户名列表。如果API调用未发生TypeError:无法读取未定义错误的属性“charAt”,因为没有输入json。我的代码如下Javascript 如何避免类型错误:无法读取属性';查拉特';当json输入不可用时的未定义值?,javascript,reactjs,charat,Javascript,Reactjs,Charat,我有一个显示用户名字第一个字母的化身。API调用时会出现用户名列表。如果API调用未发生TypeError:无法读取未定义错误的属性“charAt”,因为没有输入json。我的代码如下 <Avatar style={{ color: "#ffffff", backgroundColor: "#5e206e" }} > {item.
<Avatar
style={{ color: "#ffffff", backgroundColor: "#5e206e" }}
>
{item.user != null ? item.user.charAt(0) : "UU"}
</Avatar>
{item.user!=null?item.user.charAt(0):“UU”}
用户仍然可以未定义并抛出错误。我还将首先检查用户
我建议使用ES2020中引入的可选链接
<Avatar style={{ color: "#ffffff", backgroundColor: "#5e206e" }}>
{item?.user ? item.user.charAt(0) : "UU"}
</Avatar>
{item?.user?item.user.charAt(0):“UU”}
用户仍然可以未定义并抛出错误。我还将首先检查用户
我建议使用ES2020中引入的可选链接
<Avatar style={{ color: "#ffffff", backgroundColor: "#5e206e" }}>
{item?.user ? item.user.charAt(0) : "UU"}
</Avatar>
{item?.user?item.user.charAt(0):“UU”}
你甚至可以像item?.user?.charAt(0)| |“UU”
你甚至可以像item?.user?.charAt(0)| |“UU”