javascript ImmutableJS Map() 和 fromJS() 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33312922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:21:06  来源:igfitidea点击:

What is the difference between ImmutableJS Map() and fromJS()?

javascriptimmutable.js

提问by sowdri

var a = {address: {postcode: 5085}}

var b = Immutable.fromJS(a)
var c = b.setIn(['address', 'suburb'], 'broadview').toJS(); // no error
console.log(c); 

var d = Immutable.Map(a);
var e = d.setIn(['address', 'suburb'], 'broadview').toJS(); // error invalid keyPath(…)

Could someone explain the difference.

有人能解释一下区别吗。

Thanks,

谢谢,

回答by Samu Joseph

In this example,

在这个例子中,

var a = {address: {postcode: 5085}}
var d = Immutable.Map(a);

Here, d.get('address')is immutable. It's value cannot change to any other objects. We can only create a new Object from the existing object using the Immutable.Map.set()function of ImmutableJS.

在这里,d.get('address')是不可变的。它的值不能更改为任何其他对象。我们只能使用Immutable.Map.set()ImmutableJS的功能从现有对象创建一个新对象。

But, the object referenced by d.get('address')i.e, {postcode:5085}is a standard JavaScript object. It is mutable. A statement like this can alter the value of postcode:

但是,ie引用d.get('address'){postcode:5085}对象是标准的 JavaScript 对象。它是可变的。像这样的语句可以改变 的值postcode

d.get('address').postcode=6000;

If you check the value of d again, you can see that he value has been changed.

如果再次查看d的值,可以看到他的值已经改变了。

console.log(JSON.stringify(d));   //Outputs {"address":{"postcode":6000}}

which is against the principles of immutability.

这违反了不变性原则。

The reason is that ImmutableJS data structures like Listand Mapimparts the immutability feature to only the level-1 members of the List/Map.

原因是 ImmutableJS 数据结构喜欢List并将Map不变性特性赋予List/的第 1 级成员Map

So, if you have objects inside arrays or arrays inside objects and want them too to be immutable, your choice is Immutable.fromJS.

因此,如果您在数组内有对象或在对象内有数组并希望它们也是不可变的,那么您的选择是Immutable.fromJS.

var a = {address: {postcode: 5085}}
var b = Immutable.fromJS(a);
b.get('address').postcode=6000;
console.log(JSON.stringify(b));   //Outputs {"address":{"postcode":5085}}

From the above example you can clearly know how fromJSmakes the nested members immutable.

从上面的例子你可以清楚地知道如何fromJS使嵌套成员不可变。

I hope you understood the difference between Mapand fromJS. All the best =)

我希望你明白之间的差别MapfromJS。一切顺利 =)

回答by timetofly

fromJSdoes a deep conversion. That is, it'll recurse through all the keys and convert all elements to Lists, Maps, etc.

fromJS进行深度转换。也就是说,它将遍历所有键并将所有元素转换为列表、地图等。

In your second example, addressis a plain object, not an ImmutableJS object, so you cannot use setInto change its value.

在您的第二个示例中,address是一个普通对象,而不是 ImmutableJS 对象,因此您不能使用setIn更改其值。