Is user a callback function and how does it work?

huangapple go评论60阅读模式
英文:

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;
  }, []);

huangapple
  • 本文由 发表于 2023年5月11日 10:22:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76223733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定