简体   繁体   English

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

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

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, 谢谢,

In this example, 在这个例子中,

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

Here, d.get('address') is immutable . 这里, d.get('address')是不可变的 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. 我们只能使用Immutable.Map.set()函数从现有对象创建一个新Object。

But, the object referenced by d.get('address') ie, {postcode:5085} is a standard JavaScript object. 但是, d.get('address')引用对象,即{postcode:5085}是一个标准的JavaScript对象。 It is mutable . 这是可变的 A statement like this can alter the value of postcode : 像这样的声明可以改变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 List and Map imparts the immutability feature to only the level-1 members of the List / Map . 原因是像ListMap这样的ImmutableJS数据结构只赋予List / Map的level-1成员不变性特征。

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 fromJS makes the nested members immutable. 从上面的例子中你可以清楚地知道fromJS如何使嵌套成员不可变。

I hope you understood the difference between Map and fromJS . 我希望你理解MapfromJS之间的区别。 All the best =) 一切顺利=)

fromJS does a deep conversion. fromJS做了很深的转换。 That is, it'll recurse through all the keys and convert all elements to Lists, Maps, etc. 也就是说,它将通过所有键递归并将所有元素转换为列表,地图等。

In your second example, address is a plain object, not an ImmutableJS object, so you cannot use setIn to change its value. 在第二个示例中, address是一个普通对象,而不是ImmutableJS对象,因此您不能使用setIn来更改其值。

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

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