[英]In React, Firebase auth user is null every time I refresh the page
我被下面的问题困住了。 我经历了几个与同一问题相关的问题和答案,但没有一个对我有用。
我正在使用 firebase.auth().onAuthStateChanged 来检查用户是否已经登录,但每当我刷新页面时,我总是让用户为空。
PFB代码
import React, { Component } from 'react';
import Header from './Header';
import Home from './Home/components/Home';
import Footer from './Footer/components/Footer';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { BrowserRouter as Router, Route, Redirect, withRouter, Switch } from 'react-router-dom';
import { auth } from '../firebase/auth';
import Dashboard from './Dashboard/components/Dashboard';
import * as actions from '../actions/index';
import {Map, List, fromJS} from 'immutable';
class App extends Component {
constructor(props){
super(props);
this.state = {
loading: true,
authenticated: false,
user: null
}
}
componentDidMount() {
auth.onAuthStateChanged(user => {
//user is null every time I refresh the page
if (user) {
this.props.userLoading(false);
this.props.authUser(true);
this.props.storeUser(user.providerData);
this.props.history.push('/dasboard');
} else {
this.props.userLoading(false);
this.props.authUser(false);
this.props.history.push('/');
}
});
}
componentWillUnMount(){
this.unSubscribe();
}
render(){
const { authenticated, loading } = this.state;
return(
<div>
<Header />
<Router>
<div>
<Route path='/' exact component={Home}/>
<Route path='/dashboard' component={Dashboard} />
</div>
</Router>
<Footer />
</div>
)
}
}
const mapStateToProps = state => {
const user = state.getIn(['user', 'data'], List());
const authenticate = state.getIn(['user', 'auth'], false);
const userLoading = state.getIn(['user', 'loading'], false);
return {
user,
authenticate,
userLoading
};
}
const actionsToProps = {
storeUser: actions.storeUser,
authUser: actions.authUser,
userLoading: actions.userLoading
}
export default withRouter(connect(mapStateToProps, actionsToProps)(App))
auth.js:
import firebase from './firebase';
export const auth = firebase.auth();
export const logout = firebase.auth().signOut();
export const githubProvider = firebase.firebase_.auth.GithubAuthProvider();
export const twitterProvider = new firebase.firebase_.auth.TwitterAuthProvider();
export const facebookProvider = new firebase.firebase_.auth.FacebookAuthProvider();
我正在使用 Firebase 版本 5.8.3。
我尝试了很多可能性,比如使用 async await、setTimeout,但它们都不起作用。
您似乎要退出 auth.js:
firebase.auth().signOut();
Firebase 将注销操作排入队列,并在 Auth 实例准备就绪时运行它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.