通过不可变对普通对象进行深度访问 [英] deep access in plain objects with Immutable

查看:59
本文介绍了通过不可变对普通对象进行深度访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下示例:

const stickers = 
  new OrderedMap().set(1, {hero: "batman", name: "Bruce"});

stickers.getIn([1]); //=> { hero: 'batman', name: 'Bruce' }

stickers.getIn([1, "hero"]); //=> undefined

为什么第二个getIn的结果不确定?

Why is the result of that second getIn undefined?

关于ImmutableJS的文档状态:

The docs on ImmutableJS state:

纯JavaScript对象或数组可以嵌套在Immutable.js集合中,并且getIn()也可以访问这些值

Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and getIn() can access those values as well

因此,由此可见,如果OrderedMap的值是纯javascript对象或不可变集合,则没有区别-但是,我们可以看到,如果先将那个普通对象转换为不可变集合,则该错误消失了:

Therefore, it follows that it makes no difference if value of the OrderedMap is a plain javascript object or an Immutable collection - however we can see that the bug goes away if we convert that plain object to an Immutable Collection first:

const stickers = 
  new OrderedMap().set(1, fromJS({hero: "batman", name: "Bruce"}));

stickers.getIn([1]); //=> { hero: 'batman', name: 'Bruce' }

stickers.getIn([1, "hero"]); //=> 'batman'

推荐答案

我相信这是因为您正在寻找的文档是比您正在使用的库新版本的文档.我刚刚用4.0.0-rc.9版本试用了您的代码,它可以按预期工作.

I believe this is because you're looking at the docs for a newer version of the library than you're using. I just tried out your code with version 4.0.0-rc.9 and it works as expected.

例如:

const stickers =
  Immutable.OrderedMap().set(1, {
    hero: "batman",
    name: "Bruce"
  });

console.log(stickers.getIn([1]));

console.log(stickers.getIn([1, "hero"])); // 

<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/4.0.0-rc.9/immutable.js"></script>

这篇关于通过不可变对普通对象进行深度访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆