问题
I'm a bit confused over the firebase
function 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");
}
});
}
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?)
回答1:
onAuthStateChanged(nextOrObserver, error, completed) returns function()
returns a listener 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 // 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
}
来源:https://stackoverflow.com/questions/49811230/how-do-i-properly-use-onauthstatechanged-from-firebase-in-react-native