【问题标题】:Firebase, react and redux wait for store to updateFirebase、react 和 redux 等待 store 更新
【发布时间】:2017-12-07 21:25:01
【问题描述】:

我有一个连接到 Firebase 的 React 应用程序,我想检查用户是否在每次页面刷新时都登录,调度 IS_SIGNED_IN 动作,这是动作创建者:

export function checkAuth() {
return dispatch => {
    firebaseAuth().onAuthStateChanged((user) => {
        if (user) {
            dispatch(signedInAction())
        } else {
            dispatch(signedOutAction())
        }
    })
  }
}

在减速器内部,我只是将布尔值 isAuthenticated 设为真/假:

case ActionTypes.isSignedIn: {
    return Object.assign({}, state, {
        isAuthenticated: true
    })
}
case ActionTypes.isSignedOut: {
    return Object.assign({}, state, {
        isAuthenticated: false
    })
}

因为我想在应用加载时检查用户是否登录,所以我在componentDidMount 发送操作(我猜这是错误的):

class Main extends Component {

constructor(props) {
    super(props);
}

componentDidMount() {
    store.dispatch(checkAuth());
}

render() {
    return (
        <Provider store={store}>
            <Router>
                <Theme>
                    <Routes />
                </Theme>
            </Router>
        </Provider>
    );
  }
}

这使我检查isAuthenticated 的代码失败,因为它尚未在商店中设置,例如在Routes 组件中。解决这个问题的最佳方法是什么?总而言之,我知道我可以使用条件渲染并检查 isAuthenticated 的定义时间,但我不喜欢那个解决方案。想法?谢谢

【问题讨论】:

  • 您可以使用 componentWillMount 代替 componentDidMount 并使用条件渲染:)

标签: reactjs firebase authentication redux redux-thunk


【解决方案1】:

我已经完成了您对实时应用程序所做的事情,并在其中使用了 Firebase Auth。您需要将 Actions 用作登录和注销,然后使用 componentWillMount() 和 componentWillReceiveProps() 检查用户是否已登录:

动作:

import { auth } from '../fire';
export const GET_USER = 'get_user';

export function getUser(){
    return dispatch => {
        auth.onAuthStateChanged(user=>{
            dispatch({
                type: GET_USER,
                payload: user
            });
        });
    };
}

export function login(email,password){
    return dispatch => auth.signInWithEmailAndPassword(email, password);
}

export function logout(){
    return dispatch => auth.signOut();
}

export function createAccount(email, password){
    return dispatch => auth.createUserWithEmailAndPassword(email, password);
}

你的 Reducer 应该有这个:

import {GET_USER} from '../Actions/UserActions';

export default function( state = {loading:true}, action){
    switch (action.type){
        case GET_USER:
            return { loading: false, ...action.payload };
        default:
        return state;
    }
}

例如,在你的 App.js 中,在它的开头使用这个:

 componentWillMount(){
   this.props.getUser();
   if(this.props.user.loading === false && this.props.user.email === undefined){
     this.props.history.replace('/Login');
   }
 }

 componentWillReceiveProps(nextProps){
  if(nextProps.user.loading === false && nextProps.user.email === undefined){
    this.props.history.replace('/Login');
  }
 }

这是因为你的 props 中已经有了 Auth 凭据。

我希望这对你有用..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2019-08-07
    • 2018-06-18
    • 2020-08-10
    • 2017-06-12
    相关资源
    最近更新 更多