【问题标题】:How do I properly use onAuthStateChanged from firebase in react native?如何在原生反应中正确使用来自 firebase 的 onAuthStateChanged?
【发布时间】:2018-04-13 07:08:23
【问题描述】:

我对@9​​87654321@ 函数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(user) 块是在用户登录时触发的,但 console.log 也是在创建新帐户时触发的。如何创建仅在登录时触发的条件(而不是通过创建新帐户?)

【问题讨论】:

  • 你在使用什么 react-native-firebase 或 web APIs (Expo)??
  • react-native-firebase :)
  • 在firebase中创建一个新用户会自动登录该用户。这就是它触发的原因。
  • @André Kool 啊,我明白了,那么它触发是有道理的,谢谢:)

标签: firebase react-native firebase-authentication


【解决方案1】:
onAuthStateChanged(nextOrObserver, error, completed) returns function()

返回一个监听器函数

因此,当组件被挂载时,你需要listen,当组件被卸载时,你需要unlisten

如果你想专门监听登录,你需要制作一个单独的组件

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
}

【讨论】:

    猜你喜欢
    • 2017-06-09
    • 2018-09-27
    • 1970-01-01
    • 2019-07-26
    • 2021-05-28
    • 2019-04-23
    • 2016-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多