【发布时间】:2019-07-10 00:31:00
【问题描述】:
我遇到了以下问题。我经历了几个与同一问题相关的 SO 问题和答案,但没有一个对我有用。
我正在使用 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,但它们都不起作用。
【问题讨论】:
-
您的 firebase 版本是什么?在 v4.0.0 之后,事件发生了一些变化。你可以阅读它here
-
@bennygenel 感谢您的评论。我使用的是 5.8.3 版
-
尝试在授权域下添加您的域
-
@ManzurulHoqueRumi 你是说火力基地吗?
-
是的,在 firebase 中。
标签: reactjs firebase firebase-authentication