如何在反应原生中正确使用firebase中的onAuthStateChanged?

时间:2018-04-13 07:08:24

标签: firebase react-native firebase-authentication

我对firebase函数onAuthStateChanged()感到有些困惑。

componentDidMount() {
fbAuth.onAuthStateChanged(function(user) {
  if (user) { //THIS TRIGGERS BOTH AT LOGIN AND REGISTRATION
    console.log("LOGGED IN");
  } else {
    //TRIGGERS WHEN LOGGING OUT; NOT WHEN FAILING TO LOGIN!
    console.log("LOGGED OUT");
  }
});
}

我认为在用户登录时触发了if(用户)块,但是在创建新帐户时也触发了console.log。如何创建仅在登录时触发的条件(而不是通过创建新帐户?)

1 个答案:

答案 0 :(得分:0)

onAuthStateChanged(nextOrObserver, error, completed) returns function()

返回侦听器功能

因此,当组件已安装时需要listen,而组件卸载时需要unlisten

如果您想专门收听Login

,则需要创建一个单独的Component

Login.js //或者您的登录组件

componentDidMount() {
    // Bind the variable to the instance of the class.
    this.authFirebaseListener = firebase.auth().onAuthStateChanged((user) => {
      this.setState({
        loading: false,  // For the loader maybe
        user, // User Details
        isAuth: true
      });
    });

  }

componentWillUnmount() {
   this.authFirebaseListener && this.authFirebaseListener() // Unlisten it by calling it as a function
}