ngrx- default values being overwritten through spread operator?

此生再无相见时 提交于 2019-12-11 08:46:03

问题


I am working on an ngrx selector that converts a section of the state tree into a view model. As a simple example, in my state tree I have an array of manager. Thus I have the following setup for my state tree, and view model-

export interface Manager {
    id: string,
    name: string
}

export interface AppState {
    managers: Manager[]
}

export interface ManagersVM {
    byId: {[key: string]: Manager},
    allIds: string[]
}

export const defaultManagersVM: ManagersVM {
    byId: {},
    allIds: []
};

Then in my selector, I have:

export const selectManagersVM = createSelector(selectManagers, (data) => {
    let mgrsVM: ManagersVM = { ...defaultManagersVM };
    for(let mgr of data.managers) {
        mgrsVM.byId[mgr.id] = mgr;
        mgrsVM.allIds.push(mgr.id);
    }
})

The problem I am running into, is that the line:

let mgrsVM: ManagersVM = { ...defaultManagersVM };

seems to not be making a copy of defaultManagersVMs properties. (a console.log of defaultManagersVM after running the selector shows that it now has a non-empty byId and allIds). I was under the impression that the spread operator within a newly defined object would create a copy, but that appears to be wrong. How can I ensure that defaultManagersVM does not get mutated in my selector.


回答1:


The spread operator does not make a deep copy of nested objects, JavaScript does not have this functionality by default. An option is to use an external library (I.e. Lodash, which supports deep cloning).

Alternatively, you can write your own recursive deep cloning function, if you require some particular functionality that's not covered by other libraries.




回答2:


Here's a recursive deepClone method I picked up somewhere that seems to do the job

export function deepClone(state) {

  if (Array.isArray(state)) {
    const newState = [];
    for (let index = 0; index < state.length; index++) {
      const element = state[index];
      newState[index] = deepClone(element);
    }
    return newState;
  }
  if (typeof state === 'object') {
    const newState = {...state};
    Object.keys(newState).forEach(key => {
      if (newState.hasOwnProperty(key)) {
        const val = newState[key];
        newState[key] = deepClone(val);
      }
    });
    return newState;
  }

  return state;
}

You may also want to apply deepFreeze to anything that should not mutate. You get an error, but at least it's at the point of mutation.

export function deepFreeze (o) {
  Object.freeze(o);

  Object.getOwnPropertyNames(o).forEach((prop) => {
    if (o.hasOwnProperty(prop)
    && o[prop] !== null
    && (typeof o[prop] === 'object')
    && !Object.isFrozen(o[prop])) {
      deepFreeze(o[prop]);
    }
  });

  return o;
}


来源:https://stackoverflow.com/questions/50103170/ngrx-default-values-being-overwritten-through-spread-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!