问题
Consider the following example:
const stickers =
new OrderedMap().set(1, {hero: "batman", name: "Bruce"});
stickers.getIn([1]); //=> { hero: 'batman', name: 'Bruce' }
stickers.getIn([1, "hero"]); //=> undefined
Why is the result of that second getIn
undefined?
The docs on ImmutableJS state:
Plain JavaScript Object or Arrays may be nested within an Immutable.js Collection, and getIn() can access those values as well
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'
回答1:
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.
For example:
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>
来源:https://stackoverflow.com/questions/49025635/deep-access-in-plain-objects-with-immutable