英文:
Cannot read properties of undefined only on refresh
问题
在使用Firebase和React设置配置文件时,我遇到了Cannot read properties of undefined: (reading 'name')
错误。然而,奇怪的是,这种情况发生在我保存更改后刷新页面时,我很好奇为什么会发生这种情况。
以下是我的当前代码:
useEffect(() => {
onAuthStateChanged(auth, async (user) => {
if (user) {
const snapshot = await getDoc(doc(db, "users", user.uid));
console.log(snapshot.data().name);
const userData = snapshot.data();
setProfile(userData);
}
});
}, []);
return (
<>
<Card>
<Card.Body>
<h2 className="text-center mb-4"> Profile</h2>
<p className="details">
{JSON.stringify(profile.name)}
</p>
{error && <Alert variant="danger">{error}</Alert>}
</Card.Body>
</Card>
<div className="w-100 text-center mt-2">
<Button variant="link" onClick={handleLogout}>
{" "}
Log out{" "}
</Button>
</div>
</>
);
目前,我将继续使用JSON.stringify(profile)
,因为它能正常工作,但我只是对这个问题感到好奇。
英文:
While setting up a profile using firebase and react, I am getting the error of Cannot read properties of undefined: (reading 'name')
However, the strange part is that this doesn't happen when I save my changes but when I refresh the page. I am curious, why is this happening?
Here is before refresh(when my work is saved):
Here is after I refresh the localhost:
Here is my current code:
useEffect(() => {
onAuthStateChanged(auth, async (user) => {
if (user) {
const snapshot = await getDoc(doc(db, "users", user.uid))
console.log(snapshot.data().name)
const userData= snapshot.data();
setProfile(userData);
}
});
}, []);
return (
<>
<Card>
<Card.Body>
<h2 className="text-center mb-4"> Profile</h2>
<p className="details">
{JSON.stringify(profile.name)}
</p>
{error && <Alert variant="danger">{error}</Alert>}
</Card.Body>
</Card>
<div className="w-100 text-center mt-2">
<Button variant="link" onClick={handleLogout}>
{" "}
Log out{" "}
</Button>
</div>
</>
);
};
For now, I'll continue to just use JSON.stringify(profile)
as that works fine but just was curious on this issue.
答案1
得分: 1
Cannot read properties of undefined: (reading 'name')
这个错误意味着,没有名为 name
的可用属性。你面临这个问题是因为在第一次呈现DOM时没有API数据,然后才调用 useEffect
。
要解决这个问题,你可以使用以下方法:
-
可选链接:像这样
profile?.name
-
使用条件渲染:
{profile?.name && (<p className="details">{JSON.stringify(profile.name)}</p>)}
对于这种类型的错误,始终使用这些方法。
英文:
Cannot read properties of undefined: (reading 'name')
This error means, no property available with name
. This problem you facing bcoz DOM is render first time without the api data then useEffect
called.
To resolve the problem you can use
-
Optional Chaining :- Like this
profile?.name
-
Use conditional rendering:-
{profile?.name && (<p className="details"> {JSON.stringify(profile.name)} </p>)}
Always use these for this type of error.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论