如何使用Object.assign在React中使状态不可变?

时间:2016-04-16 08:47:30

标签: javascript reactjs

我一直致力于反应,我开始知道我们不应该直接改变状态,因为它不会渲染组件。相反,我们应该使用setState方法。为此,我们需要将整个对象复制到另一个对象然后更改元素,但它可能非常昂贵。我听说Object.assign有助于这样做,还有什么最好的方法呢?

1 个答案:

答案 0 :(得分:0)

我不知道React,但是如果你需要制作一个对象的浅表副本,Object.assign确实让你这样做:

// An original, with three properties; the third refers to an object
var theOriginal = {
  answer: 42,
  question: "Life, the Universe, and Everything",
  obj: {
    foo: "bar"
  }
};

// Make a shallow copy
var theCopy = Object.assign({}, theOriginal);

// Note that the object's properties are not linked
log("theOriginal.answer:          " + theOriginal.answer);
log("theCopy.answer:              " + theCopy.answer);
theCopy.answer = 67;
log("updated theCopy.answer:      " + theCopy.answer);

// But note that while the `obj` property was copied, both
// copies refer to the *same* object:
log("theOriginal.obj.foo:         " + theOriginal.obj.foo);
log("theCopy.obj.foo:             " + theCopy.obj.foo);
theOriginal.obj.foo = "updated";
log("updated theOriginal.obj.foo: " + theOriginal.obj.foo);
log("updated theCopy.obj.foo:     " + theCopy.obj.foo);


function log(msg) {
  var p = document.createElement('pre');
  p.appendChild(document.createTextNode(msg));
  document.body.appendChild(p);
}

示例,这也说明了我的意思"浅":



person