简体   繁体   English

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

[英]How to use Object.assign to make states immutable in React?

I have been working on react and I came to know that we should not directly mutate the states because it would not render the component. 我一直在做反应,后来我知道我们不应该直接改变状态,因为它不会渲染组件。 Instead we should use setState method. 相反,我们应该使用setState方法。 For this, we need to copy the entire object into another and then change the elements, but it can be very expensive. 为此,我们需要将整个对象复制到另一个对象中,然后更改元素,但这可能会非常昂贵。 I have heard Object.assign helps doing this, Also what is the best method to do that? 我听说Object.assign可以帮助您做到这一点,那么什么是最好的方法呢?

I don't know React, but if you need to make a shallow copy of an object, Object.assign does indeed let you do that: 我不知道React,但是如果您需要创建对象的浅表副本,那么Object.assign确实可以让您做到这一点:

var theCopy = Object.assign({}, theOriginal);

Example, which also demonstrates what I mean by "shallow": 示例,还演示了“浅”的含义:

 // 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); } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM