【问题标题】:Angular, ngrx data removed when fired dispatch event触发调度事件时删除 Angular,ngrx 数据
【发布时间】:2021-04-30 01:17:32
【问题描述】:

我有 2 个用于数据获取的 API 调用和 2 个用于 ngrx 存储中的数据存储的调度事件。

问题是当我调用第一个 FETCH_FINANCIAL_INSTITUTION 调度员和第二个 FETCH_USER_GROUPS 调度员时,机构被删除。请参阅下面的屏幕截图。

请看下面我的实现,

  1. 对于研究所,

    this.store.dispatch({
           type: Action.FETCH_FINANCIAL_INSTITUTION,
           payload: <IFinancialInstitution[]> institutions,
    });
    
  2. 对于用户组,

    this.store.dispatch({
       type: Action.FETCH_USER_GROUPS,
       payload: <IUserGroup[]> userGroups,
    });
    

这里是减速器,

  1. 研究所减速器

     export interface IFinancialInstitutionState {
       institutes: IFinancialInstitution[];
     }
    
     export class FinancialInstitutionState implements 
       IFinancialInstitutionState {
         institutes: IFinancialInstitution[] = [];
     }
    
     export function FinancialInstitutionReducer(
         state: IFinancialInstitutionState = new FinancialInstitutionState(), 
         action) {
              switch (action.type) {
                  case Action.FETCH_FINANCIAL_INSTITUTION:
                      return {...state, ...{institutes : action.payload}};
              }
     }
    
  2. 用户组缩减器

      export interface IUserGroupState {
        userGroup: IUserGroup[];
      }
    
      export class UserGroupState implements IUserGroupState {
            userGroup: IUserGroup[] = [];
      }
    
      export function UserGroupReducer (
            state: IUserGroupState = new UserGroupState(), action,
      ) {
          switch (action.type) {
                  case Action.FETCH_USER_GROUPS :
                  return {...state, ...{userGroup : action.payload}};
        }
      }
    

根减速器,

export const rootReduces = {
  authData : AuthReducer,
  usersData : UsersReducer,
  systemData : SystemReducer,
  institutesData : FinancialInstitutionReducer,
  userGroupData : UserGroupReducer,
};

AppState.ts

export interface AppState {
  readonly authData: IAuthResult[];
  readonly usersData: UserState;
  readonly systemData: SystemConfigs;
  readonly institutesData: IFinancialInstitutionState;
  readonly userGroupData: IUserGroupState;
}

【问题讨论】:

    标签: angular ngrx dispatcher state-management


    【解决方案1】:

    最后,我解决了我的问题。我把它贴在这里,它会帮助别人。

    问题在于,在我的 Reducer 函数中,switch 案例中的默认值返回的是 initialState 而不是返回状态。添加默认到switch case后问题解决了。

    export function FinancialInstitutionReducer(
       state: IFinancialInstitutionState = new FinancialInstitutionState(), action) {
            switch (action.type) {
               case Action.FETCH_FINANCIAL_INSTITUTION:
                      return {...state, ...{institutes : action.payload}};
               default:
                      return state; // this is added line
            }
     }
    

    【讨论】:

      猜你喜欢
      • 2021-01-28
      • 1970-01-01
      • 2015-07-18
      • 2012-01-30
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多