简体   繁体   English

Firebase 的 onAuthStateChanged 如何在 reactJS 的 ComponentDidMount 生命周期中工作

[英]How does firebase's onAuthStateChanged work in ComponentDidMount lifecycle in reactJS

Can anyone explain we how this onAuthStateChanged function is working inside componentDidMount.谁能解释一下这个 onAuthStateChanged function 如何在 componentDidMount 中工作。 I know this lifecycle hook get executed only once when the component is mounted.我知道这个生命周期钩子只在组件安装时执行一次。 So how does the function inside gets executed?那么里面的function是怎么执行的呢?

What I assume is it's like callback function which keeps on running in event loop as gets fired when state changed like addEventlistner in JS.我假设它就像回调 function 继续在事件循环中运行,因为当 state 像 JS 中的 addEventlistner 一样更改时会被触发。

componentDidMount() {
    console.log("Context Mounted");
    firebaseapp.auth().onAuthStateChanged((user) => {
      if (user) {
        this.setState({ currentUser: user });
        console.log("User Signed IN ");
      } else {
        console.log("THERE IS NO USER");
      }
    });
  }

You pretty much got the gist of it: after your register your onAuthStateChanged callback with Firebase it will be called:你几乎明白了它的要点:在你用 Firebase 注册你的onAuthStateChanged回调后,它将被调用:

  1. "immediately" with the current authentication state “立即”使用当前身份验证 state
  2. whenever that authentication state changes每当身份验证 state 更改时

Since you call setState to put the user into the state, this then triggers a rerender of the UI whenever one of the above events occurs.由于您调用setState将用户放入 state,因此只要发生上述事件之一,就会触发 UI 的重新呈现。

This continues until the app exits or until your unregister the listener, which you should typically do in the componentWillUnmount method of the same component.这一直持续到应用程序退出或直到您取消注册侦听器,您通常应该在同一组件的componentWillUnmount方法中执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM