【问题标题】:How to avoid mutation of the object in thunks如何避免 thunk 中对象的突变
【发布时间】:2019-05-18 08:09:20
【问题描述】:

我想在每次调用我的操作时创建一个新的object。我现在已经通过使用Object.assign 实现了这一点,但是有没有更好的方法来实现这一点,因为Object.assign 不是深拷贝?

export const addPlayer: Thunk = (players: any[], name: string) => (
  dispatch,
  getState
) => {
  const state = Object.assign({}, getState().players);
  errors.forEach(e => {
    state.playerQueue.push({
      player: {
        message: e.message,
        name
      }
    });
  });
  dispatch(playersAction(state));
};

【问题讨论】:

    标签: javascript typescript redux redux-thunk


    【解决方案1】:

    您可以使用JSON.parse(JSON.stringify(object));。这不是最好的方法,但您可以获得对象的深层副本。适用于小物体。

    【讨论】:

    • 谢谢,我还发现 npm 包 clone 现在可以很好地解决这个问题。
    猜你喜欢
    • 2012-02-21
    • 2017-04-28
    • 2022-07-28
    • 2020-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多