简体   繁体   English

如何从Redux状态获取嵌套数组值

[英]How to get a nested array value from a redux state

This function returns the redux state 该函数返回redux状态

this.context.store.getState()

Here's the state 这是状态

Map {size: 2, _root: ArrayMapNode, __ownerID: undefined, __hash: undefined, __altered: false}

If I do this.context.store.getState()["size"] it will return 2, which is perfect. 如果我执行this.context.store.getState()[“ size”],它将返回2,这是完美的。 Now I want to retrieve place_id from the following. 现在,我想从以下位置检索place_id。 How do I do it? 我该怎么做?

{_root:
  entries:
    [place_id: 'TRYING TO GET THIS VALUE"

But if I do getState()["_root"]["entries"]["place_id"] it doesn't work (because it's within an array?) 但是,如果我执行getState()[“ _ root”] [“ entries”] [“ place_id”],则它不起作用(因为它在数组中?)

entries is an array, meaning it may contain multiple objects. entries是一个数组,表示它可能包含多个对象。 You need to select the object by index. 您需要按索引选择对象。 So for example, if you were to get the ID of the first place, your code would look like this: 因此,例如,如果要获取第一名的ID,则代码将如下所示:

getState()._root.entries[0].place_id

Or 要么

getState()["_root"]["entries"][0]["place_id"]

Be aware that if you try to access a property of an object that doesn't exist, your code will break. 请注意,如果尝试访问不存在的对象的属性,则代码将中断。 So you need to check if the property exist before accessing it - How do I check if an object has a property in JavaScript? 因此,您需要在访问属性之前先检查该属性是否存在- 如何检查对象在JavaScript中是否具有属性?

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

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