如何防止对象/数组突变?

时间:2016-01-17 15:55:41

标签: javascript typescript immutability angular angular2-routing

我一直在尝试调试奇怪的问题,我终于弄清楚它为什么会发生。只是不确定如何防止它(;我有这个功能:

getInfo(id) {
  id = id || "zero";
  let i = routeDefinitions.findIndex(r => Boolean(r.name.toLowerCase().match(id)));
  // console.log(i) - works in plunker
  // but in my app sometimes returns -1...
  let current = routeDefinitions[i];
  let next = routeDefinitions[i + 1] ? routeDefinitions[i + 1] : false;
  let prev = routeDefinitions[i - 1] ? routeDefinitions[i - 1] : false;
  return { prev, current, next };
}

..它在this plunker中完美运行,但在我的应用程序中,我使用其返回值来更新应用程序状态(redux模式的自定义实现)。当我通过此函数发送返回值时:

  private _update(_old, _new) {
    let newState = Object.keys(_new)
      .map(key => {
        if (_old[key] === undefined) {
          _old[key] = _new[key];
        } else if (typeof _new[key] === "object") {
          this._update(_old[key], _new[key]);
        } else {
          _old[key] = _new[key];
        }
        return _old;
      })
      .find(Boolean);

    return Object.assign({}, newState || _old);
  }

.. routeDefinitions阵列发生变异,事情开始破裂......我尝试了几件事:

let current = [...routeDefinitions][i];
// and:
return Object.assign({}, { prev, current, next });

..但它没有用。如何防止routeDefinitions数组的变异?

编辑:我设法重现了this plunker

中的错误

2 个答案:

答案 0 :(得分:0)

  

routeDefinitions数组发生变异,事情开始中断

如果你的功能是真的:

getInfo(id) {
  id = id || "zero";
  let i = routeDefinitions.findIndex(r => Boolean(r.name.toLowerCase().match(id)));
  // console.log(i) - works in plunker
  // but in my app sometimes returns -1...
  let current = routeDefinitions[i];
  let next = routeDefinitions[i + 1] ? routeDefinitions[i + 1] : false;
  let prev = routeDefinitions[i - 1] ? routeDefinitions[i - 1] : false;
  return { prev, current, next };
}

然后routeDefinitions 未发生变异。其他东西正在改变routeDefinitions。

答案 1 :(得分:0)

我通过修改_update()来解决这个问题:

  private _update2(_old, _new) {
    let newState = {}; 
    Object.keys(_new)
      .map(key => {
        if (_old[key] === undefined) {
          newState[key] = _new[key];
        } else if (typeof _new[key] === "object") {
          newState[key] = this._update2(_old[key], _new[key]);
        } else {
          newState[key] = _new[key];
        }
        return newState;
      })
      .find(Boolean);

    return Object.assign({}, _old, newState);
  } 

我只使用old state来检查值,不要在_update()完成后再修改它。

Plunker