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

编程入门 行业动态 更新时间:2024-10-16 00:26:07
本文介绍了ImmutableJS Map()和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.

谢谢

推荐答案

在此示例中,

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

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

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')引用的对象(即{postcode:5085})是标准的JavaScript对象.它是可变的.这样的语句可以更改postcode的值:

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:

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

如果再次检查d的值,则可以看到他的值已更改.

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

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

这违反了不变性原则.

which is against the principles of immutability.

原因是像List和Map这样的ImmutableJS数据结构将不可变性功能仅赋予List/Map的1级成员.

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.

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

So, if you have objects inside arrays or arrays inside objects and want them too to be immutable, your choice is 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}}

从上面的示例中,您可以清楚地了解fromJS如何使嵌套成员不可变.

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

我希望您了解Map和fromJS之间的区别.一切顺利=)

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

更多推荐

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

本文发布于:2023-11-25 07:46:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么区别   ImmutableJS   Map   fromJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!