首页 > 解决方案 > Redux 状态正在被 lodash 的 mergeWith 改变

问题描述

我正在使用 lodashmergeWith将一些有效负载数据合并到我的一些 redux 状态中。但是,这样做时,我最终会直接改变状态。我不明白这是怎么发生的,因为我{...state}用来进行合并。为什么会发生这种情况,我该怎么做才能不直接改变我的状态?您可以查看以下代码段,了解正在发生的事情的示例。谢谢!

const merger = (objectOne, objectTwo) => {
  const customizer = (firstValue, secondValue) => {
    return _.isArray(firstValue) ? secondValue : undefined;
  };

  return _.mergeWith(objectOne, objectTwo, customizer);
};

const state = {
  1: {a: true, b: true, c: true},
  2: {a: true, b: true, c: true},
  3: {a: true, b: true, c: true},
}

const payload = {
   2: {a: true, b: false, c: true},
}

console.log("Merged data:");
console.log(merger({...state}, payload));
console.log("Manipulated state:");
console.log(state);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

标签: javascriptreduxlodash

解决方案


您必须知道,扩展语法{ ...state }只对您的对象进行浅拷贝。所以事实上 - 深层嵌套的属性 - 在您的特定情况下{ a: true, b: true, c: true },通过引用保持相同的对象。如果您希望避免状态突变错误,您应该使用cloneDeeplodash 中的 eg 函数。

merger(_.cloneDeep(state), payload);


推荐阅读