Reactjs 为什么每次我都需要检查react中的变量值?
我正在处理react,当页面刷新时,getReactjs 为什么每次我都需要检查react中的变量值?,reactjs,Reactjs,我正在处理react,当页面刷新时,get配置文件有时为null错误。为此,我将所有代码放入if中 useEffect(() => { getCurrentProfile(); if(user && profile){ setFormData({ name:user && user[0].name, phone: loading || !profile[0].phone ? '' : profile[0].phone, c
配置文件有时为null
错误。为此,我将所有代码放入if
中
useEffect(() => {
getCurrentProfile();
if(user && profile){
setFormData({
name:user && user[0].name,
phone: loading || !profile[0].phone ? '' : profile[0].phone,
company: loading || !profile[0].company ? '' : profile[0].company,
website:loading || !profile[0].website ? '' : profile[0].website,
});
}
}, [loading, getCurrentProfile]);
在这里您可以看到,如果我没有设置如果(用户和配置文件)
条件,那么我得到的配置文件为null
错误
我正在写一个糟糕的代码,或者这只是编写它的唯一方法?
useEffect(() => {
const user = getCurrentProfile();
if(user){
setFormData({
name:user && user[0].name,
phone: loading || !profile[0].phone ? '' : profile[0].phone,
company: loading || !profile[0].company ? '' : profile[0].company,
website:loading || !profile[0].website ? '' : profile[0].website,
});
}
}, [loading, getCurrentProfile]);
useEffect(() => {
getCurrentProfile();
if(user && profile){
setFormData({
name:user && user[0].name,
phone: loading || !profile[0].phone ? '' : profile[0].phone,
company: loading || !profile[0].company ? '' : profile[0].company,
website:loading || !profile[0].website ? '' : profile[0].website,
});
}
}, [user, profile, loading, getCurrentProfile]);
useEffect内部有一个闭包,它将读取您的用户和配置文件,因此您将得到null,包括在dependencie数组[user,profile,loading,getCurrentProfile])中,或者在getCurrentProfile函数中返回您的用户数据我不确定问题是什么,您是否在寻求其他方法来检查
null
?您所做的是一个完全有效的空检查,如果您认为变量此时不应为空,那么您可能会在代码后面遇到问题(例如,在getCurrentProfile
)