如何获取要显示的 Firestore 文档字符串?无法执行状态更新,异步功能正在使用效果



我有一个AuthProvider/上下文提供firebase身份验证。在较低的组件中,我试图呈现来自Firestore的当前用户数据,例如用户名,当他们登录时。

export function AuthProvider({ children }) {
function login(email, password) {
return auth.signInWithEmailAndPassword(email, password)
}
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged(user => {
setCurrentUser(user);
setLoading(false);
if (currentUser) {
const docRef = db.collection("users").doc(currentUser.uid);
docRef.get().then(function(doc){
if(doc && doc.exists) {
setCurrentUsername(doc.data().username);
console.log(currentUsername)
}
}).catch(function(error) {
console.log("no document:", error);
});
} else {
// no user logged in
};
})
return unsubscribe
}, [login])
const value = {
currentUser, //firebase
signup,
login,
logout,
resetPassword,
currentFullname,
currentUsername,
currentEmail,
loading,
setLoading,
}
return (
<AuthContext.Provider
value={value}>
{children}
</AuthContext.Provider>
)
}
async function handleLogin(e) {
e.preventDefault()
try {
setError("")
setLoading(true)
await login(emailRef.current.value, passwordRef.current.value)
} catch {
setError("Incorrect email or password")
}
setLoading(false)
}

只有在登录时,我想从Firebase获取额外的用户信息,因为Firebase身份验证只有uid和电子邮件。我得到"无法在卸载的组件上执行React状态更新";错误。

Firestore数据的结构如下:collection("users")—>文档(firebase uid)——>用户名:someUsername,名:bobSmith等

修复!代码现在为我工作,并已更新,以帮助任何未来的人。

我忘了传入一个useContext值prop。

然后我将useEffect依赖数组更改为login。谢谢Drew给我的指导!

最新更新