在React中,每次刷新页面时,Firebase身份验证用户都为null

时间:2019-02-15 20:22:49

标签: reactjs firebase firebase-authentication

我遇到了以下问题。我经历了几个与同一问题相关的SO问题和答案,但没有一个对我有用。

我正在使用firebase.auth()。onAuthStateChanged来检查用户是否已经登录,但是每次刷新页面时,我总是会得到用户null。

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。

我尝试了很多可能性,例如使用异步等待,setTimeout,但是它们都没有起作用。

1 个答案:

答案 0 :(得分:1)

您似乎正在auth.js中注销:

firebase.auth().signOut();

Firebase对退出操作进行排队,并在Auth实例就绪时运行它。