简体   繁体   中英

How to get a nested array value from a redux state

This function returns the redux state

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. Now I want to retrieve place_id from the following. 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?)

entries is an array, meaning it may contain multiple objects. 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:

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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