【问题标题】:Change the 'Loading' state from another reducer从另一个减速器更改“加载”状态
【发布时间】:2019-02-14 12:01:16
【问题描述】:

我有一个 authReducer 和用户状态。 我还有一个generalReducer,其状态与错误通知消息和加载真/假有关。

当在单独的 reducer 中加载登录或其他任务时,如何从一个与另一个 reducer 相关的 reducer 修改或创建全局 loading 状态变量?

generalReducer.js

let defaultState = {
    loading: false,
    error: null,
    notification: false,      
};

export default function generalReducer(state = defaultState, action){
switch(action.type){
    case loading:
        return {
          ...state,
          loading: action.payload.isLoading,
        };
     default:
        return state;
     }

authReducer.js

let defaultState = {
    user: {
        displayName: null,
        email: null,
        photoUrl: null,
        isAnonymous: null,
        phone: null,
    }
};

export default function authReducer(state = defaultState, action){
    switch(action.type){
    case LOGIN_BEGIN:
    case LOGOUT_BEGIN:
        return {
            ...state,
        };
    case LOGIN_FAILURE:
    case LOGOUT_FAILURE:
        return {
            ...state,
    };
    case LOGIN_SUCCESS:
    return {
        ...state,
        user: action.payload.user
    };
    default:
    return state;
    }
}

authReducer.js 中,我希望能够在generalReducer 中设置loadingerror 状态以对应所需的错误或加载状态。怎么样?

【问题讨论】:

标签: reactjs redux react-redux


【解决方案1】:

您需要从 authActions 中导入 authActionTypes 并在 generalReducer.js 中更新 reducer

generalReducer.js:

import {
  LOGIN_BEGIN,
  LOGOUT_BEGIN,
  LOGIN_FAILURE,
  LOGOUT_FAILURE,
  LOGIN_SUCCESS,
} from './authActions;

let defaultState = {
    loading: false,
    error: null,
    notification: false,      
};

export default function generalReducer(state = defaultState, action){
switch(action.type){
    case loading:
        return {
          ...state,
          loading: action.payload.isLoading,
        };
    case LOGIN_BEGIN:
    case LOGOUT_BEGIN: {
      return {
        ...state,
        loading: true,
        error: null,
      }
    }
    case LOGIN_FAILURE:
    case LOGOUT_FAILURE: {
      return {
        ...state,
        loading: false,
        error: 'Set Your Error Here',
      }
    }
    case LOGIN_SUCCESS: {
      return {
        ...state,
        loading: false,
        error: null,
      }
    }
     default:
        return state;
     }

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2021-10-13
    • 2019-06-11
    • 2017-07-03
    • 2019-04-20
    • 2019-07-06
    • 2020-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多