我想在App.js中实现Firebase登录
显然,在firebase异步登录完成之前,将从React Router调用Login Component(“/”路径将调用Login Component)
import React, {Component} from 'react';
import Layout from './containers/Layout';
import { connect } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import firebase from './firebase/firebase';
import rootReducer from './store/reducers/index';
import * as action from './store/actions/index';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
isAsnycFinished: false
};
}
componentDidMount() {
const promise = firebase.auth().signInAnonymously();
firebase.auth().onAuthStateChanged(user => {
console.log(user);
if (user) {
let loginDetails = {
isAnonymous: user.isAnonymous,
uid: user.uid,
isLoading: false,
isAsnycFinished: true
};
this.props.onUpdateLogin(loginDetails);
} else {
let loginDetails = {
isAnonymous: false,
uid: '',
isLoading: false,
isAsnycFinished: true
};
this.props.onUpdateLogin(loginDetails);
}
this.setState({
isLoading: false,
isAsnycFinished: true
});
});
}
render() {
return (
<BrowserRouter>
<Layout /> //contains Login Component as a route
</BrowserRouter>
);
}
}
const mapDispatchToProps = ( dispatch ) => {
return {
onUpdateLogin: (loginDetails) => dispatch(action.uploadLoginStatus(loginDetails))
}
}
登录组件:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
inputClassName: '',
selectClassName: '',
showLoading: true,
showError: false,
errorMessage: "",
showLoginForm: false
}
console.log('props', this.props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
....
componentDidMount() {
if(this.props.isLoading) { //from redux store
this.setState({
showLoading: this.props.isLoading,
showLoginForm: false
});
}
else {
if(this.props.isAnonymous) {
this.props.history.replace('/profile');
console.log('logged in');
}
else {
this.setState({
showLoading: false,
showLoginForm: true
});
}
}
}
所以我想在登录页面上显示加载图标 当应用程序中的异步功能完成时,登录组件可以获得新的道具吗? 如果是这样,我可以检查道具并更改登录组件中的状态。
我在Login Component中尝试了componentWillReceiveProps()。但我没有得到新的道具。
我是否需要在每个组件中调用异步函数才能使其正常工作?
减速机:
import * as actionTypes from '../actions/actionTypes';
const initialState = {
isAnonymous: false,
uid: '',
isLoading: true,
isAsyncFinished: false
}
const Auth = (state = initialState, action) => {
switch(action.type) {
case actionTypes.LOGIN_STATUS:
return (
{
isAnonymous: action.loginDetails.isAnonymous,
uid: action.loginDetails.uid,
isLoading: action.loginDetails.isLoading
}
);
default:
return state;
}
}
export default Auth;