变量在useEffect中未定义



我试图在useEffect钩子内部的函数中使用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,因为当您在钩子中设置它时,这是您(不)传递给状态的。

所以这个效果首先将undefined作为currentUser的值来运行。

之后,onAuthStateChanged将触发并更新状态。

这将触发重新渲染,currentUser将是你想要的值。

然而,你的效果将而不是重新运行,因为依赖数组是[]。你需要告诉它当值更新时重新运行这个函数。

useEffect(() => {
const fetchParticipants = async () => {
console.log(currentUser.uid) // not defined
}
fetchParticipants()
}, [currentUser]) // <-------------------- Dependancy array

最新更新