我正在嘗試在 HookcurrentUser內部的函式中使用 的值useEffect,但該值似乎不是用戶的物件,我希望它在使用時成為它。這是代碼:
function Chat() {
const currentUser = useAuth()
useEffect(() => {
const fetchParticipants = async () => {
console.log(currentUser.uid) // not defined
}
fetchParticipants()
}, [])
}
那就是useAuth()被呼叫的函式
export function useAuth() {
const [ currentUser, setCurrentUser ] = useState();
useEffect(() => {
const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
return unsub;
}, [])
return currentUser;
}
uj5u.com熱心網友回復:
的初始值currentUser將是undefined因為這是您(不)在您的鉤子中設定它時傳遞給狀態的值。
所以效果首先會以undefined的值運行currentUser。
稍后,onAuthStateChanged將觸發并更新狀態。
這將觸發重新渲染,currentUser并將成為您想要的值。
但是,您的效果不會重新運行,因為依賴陣列是[]. 您需要告訴它在值更新時重新運行該函式。
useEffect(() => {
const fetchParticipants = async () => {
console.log(currentUser.uid) // not defined
}
fetchParticipants()
}, [currentUser]) // <-------------------- Dependancy array
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489330.html
標籤:javascript 反应 火力基地
上一篇:當我使用recylceviewTextView從firebase中檢索孩子時,不會顯示
下一篇:如何將字串資料轉換為偏移資料?
