Angular 2 with ngrx / store,更新状态对象的属性而不覆盖整个对象

时间:2016-11-21 08:44:54

标签: angular typescript redux ngrx

我试图分配一个状态对象的新属性,但我似乎无法设置它而不设置一个全新的对象,我只想添加一个属性,而不是创建一个全新的对象只有那一个属性。

这是我的减速机:

const initialState = {
  all: [],
  single: {}
}

export const ModelsReducer: ActionReducer<any> = (state: IModelsStorage = initialState, action: Action) => {

  switch(action.type) {

    case GET_MODELS_SUCCESS: return Object.assign({}, state, {
      all: [...action.payload.data]
    });

    case GET_MODEL_SUCCESS: return Object.assign({}, state, {
      single: action.payload.data
    });

    // How do I only update the single object without overwriting the whole thing?
    case GET_VARIANTS_SUCCESS: return Object.assign({}, state, {
      single: {
        variants: action.payload.data
      }
    });

    default: return state;
  }
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用另一个Object.assign ...

case GET_VARIANTS_SUCCESS: return Object.assign({}, state, {
  single: Object.assign(state.single, {
    variants: action.payload.data
  })
});