英文:
Is user a callback function and how does it work?
问题
在以下代码中,我不明白 "user" 是什么。onAuthStateChangedListener 调用 onAuthStateChanged(auth, user),它是一个一直在监听的监听器。它应该是一个回调函数,但是在任何地方都没有定义 "user" 函数。我已经反复听了描述。
英文:
In the following code, I am not understanding what user is. onAuthStateChangedListener calls onAuthStateChanged(auth, user), it is a listener that is always listening. It is supposed to be a callback, but there is no user function defined anywhere. I have listened to the description over and over.
useEffect(() => {
const unsubscribe = onAuthStateChangedListener((user) => {
if (user) {
createUserDocumentFromAuth(user);
}
setCurrentUser(user);
});
return unsubscribe;
}, []);
答案1
得分: 1
在此代码中,user
不是回调函数,而是回调函数的参数。
如果我们将代码重写如下将会更有帮助。
useEffect(() => {
const authStateHandler = (user) => {
if (user) {
createUserDocumentFromAuth(user);
}
setCurrentUser(user);
}
const unsubscribe = onAuthStateChangedListener(authStateHandler);
return unsubscribe;
}, []);
英文:
In this code, user
is not callback but a parameter of callback.
It will be helpful if we rewrite the code as follows.
useEffect(() => {
const authStateHandler = (user) => {
if (user) {
createUserDocumentFromAuth(user);
}
setCurrentUser(user);
}
const unsubscribe = onAuthStateChangedListener(authStateHandler);
return unsubscribe;
}, []);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论