问题描述
我对 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(user)块,但是在创建新帐户时也会触发console.log.如何设置仅在登录时触发(而不是通过创建新帐户触发)的条件?
I thought that the if(user) block triggered when the user has logged in, but the console.log is also triggered when a new account is created. How do I make a conditional that only triggers at login (and not by creating a new account?)
推荐答案
onAuthStateChanged(nextOrObserver, error, completed) returns function()
返回一个监听器功能
因此,当安装组件时,您需要监听
;当卸载 <取消监听
Therefore you need to listen
it when the component is mounted and unlisten
when the component is unmounted
如果要专门监听登录,则需要制作一个单独的组件
You need to make a separate Component if you want to listen specifically for Login
Login.js //或您的任何登录组件都是
Login.js // Or whatever your login component is
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
}
这篇关于我如何在React Native中正确使用Firebase的onAuthStateChanged?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!