我试图在 useEffect
Hook 函数内部使用 currentUser
的值,但该值似乎不是我想要的用户对象使用它时。这是代码:
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;
}
最佳答案
currentUser
的初始值将是 undefined
,因为当您在 Hook 中设置它时,这是您(不)传递给状态的内容。
所以效果首先会以 undefined
作为 currentUser
的值运行。
稍后,onAuthStateChanged
将触发并更新状态。
这将触发重新渲染,currentUser
将是您想要的值。
但是,您的效果将不会重新运行,因为依赖项数组是[]
。您需要告诉它在值更新时重新运行该函数。
useEffect(() => {
const fetchParticipants = async () => {
console.log(currentUser.uid) // not defined
}
fetchParticipants()
}, [currentUser]) // <-------------------- Dependancy array
关于javascript - useEffect 中 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72582672/