问题
When mounting a component, I'd like to render either a log in screen or the app, depending on wether the user in logged in. However, each time I refresh, the user is logged out. How would I keep them logged in?
App Component:
firebase.initializeApp(config); //init the firebase app...
class App extends Component {//this component renders when the page loads
constructor(props){
super(props);
this.state = {user: firebase.auth().currentUser};//current user
}
render(){
if (this.state.user) {//if you are logged in
return (
<Application/>
);
} else {//if you are not logged in
return (
<Authentication/>
);
}
}
}
This is the method I'm using to log in the user (which works fine):
let email = "some";
let password = "thing";
const auth = firebase.auth();
const promise = auth.signInWithEmailAndPassword(email, password);
回答1:
The user's token is automatically persisted to local storage, and is read when the page is loaded. This means that the user should automatically be authenticated again when you reload the page.
The most likely problem is that your code doesn't detect this authentication, since your App
constructor runs before Firebase has reloaded and validated the user credentials. To fix this, you'll want to listen for the (asynchronous) onAuthStateChanged() event, instead of getting the value synchronously.
constructor(props){
super(props);
firebase.auth().onAuthStateChanged(function(user) {
this.setState({ user: user });
});
}
回答2:
I had the same issue with Firebase in React. Even though Firebase has an internal persistence mechanisms, you may experience a flicker/glitch when reloading the browser page, because the onAuthStateChanged
listener where you receive the authenticated user takes a couple of seconds. That's why I use the local storage to set/reset it in the onAuthStateChanged listener. Something like the following:
firebase.auth.onAuthStateChanged(authUser => {
authUser
? localStorage.setItem('authUser', JSON.stringify(authUser))
: localStorage.removeItem('authUser')
});
Then it can be retrieved in the constructor of a React component when the application starts:
constructor(props) {
super(props);
this.state = {
authUser: JSON.parse(localStorage.getItem('authUser')),
};
}
You can read more about it over here.
来源:https://stackoverflow.com/questions/48855851/how-do-i-keep-a-user-logged-into-firebase-after-refresh-in-react-js