【问题标题】:Trouble Merging Object with State in Angular NgRx在Angular NgRx中将对象与状态合并的问题
【发布时间】:2019-04-21 02:41:56
【问题描述】:

我阅读了本教程on creating a NgRx store,因此我创建了一个具有以下形状的简单商店。

export const initialState: IState = {
  app: initialAppState
};

export function getInitialState(): IState {
  return initialState;
}

export interface IApp {
  id?: string;
  testMode?: boolean;
  authenticated?: boolean;
  user?: User;
  role?: string;
}

export interface IAppState {
  app: IApp;
}

export const initialAppState: IAppState = {
  app: {
    id: null,
    testMode: false,
    authenticated: false,
    user: null,
    role: 'END_USER'
  }
};

它有一个动作 PatchApp 和一个看起来像这样的减速器

export const appReducers = (state = initialAppState, action: AppActions): IAppState => {
  switch (action.type) {
    case AppActionTypes.PatchApp: {
      return { ...state, app: action.payload };
    }

    default:
      return state;
  }
};

现在对我来说,这似乎超级简单。我们有一个存储在app 属性中的初始状态。如果我们得到一个有效载荷来更新现有状态的authenticated 属性,我希望reducer 只覆盖该属性而不是整个状态。

但是当我使用调试器单步调试时,我可以看到状态 get 仅使用传入的属性进行了更新。

所以如果我有这样的初始状态:

export const initialAppState: IAppState = {
  app: {
    id: null,
    testMode: false,
    authenticated: false,
    user: null,
    role: 'END_USER'
  }
};

然后我用{authenticated: true, id: 'someid'}PatchApp,我希望action.payload 覆盖/合并/修补现有对象。

取而代之的是,整个 store 都被 JUST 属性覆盖了。因此,在完成上述补丁应用程序后,我们将只设置 authenticatedid 属性。

知道为什么我的减速器没有按预期运行吗?我读了article from Flavio Copes 并没有看到任何我出错的地方。

我也尝试使用Object.assign() 来合并对象。

return Object.assign({}, state, { app: action.payload });

我有一个 CodeSandbox 来说明我要解决的问题。

https://codesandbox.io/s/oxj7xx5n35?fontsize=14

【问题讨论】:

    标签: angular typescript ecmascript-6 ngrx


    【解决方案1】:

    不确定我是否正确地尝试了您的操作,但您似乎只想修补状态的 app 部分。如果是这样,你应该这样做:

    export const appReducers = (state = initialAppState, action: AppActions): IAppState => {
      switch (action.type) {
        case AppActionTypes.PatchApp: {
          return { 
            ...state, 
            app: {...state.app, ...action.payload} 
          };
        }
    
        default:
          return state;
      }
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-27
      • 2017-08-30
      • 1970-01-01
      • 2021-06-17
      • 2019-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多