React Native: Iterate through nested objects to display values

允我心安 提交于 2021-01-29 09:45:47

问题


I want to display multiple images into a screen. My database tree looks like this:

I am also able to load the object through snapshot.val() and this is how it looks like in the console while running:

Object {
  "4aae-47bb-e0f7-36e2-7e66": Object {
    "author": "edm9AAbPpFUWrO9HDXfV442QzSE2",
    "caption": "Test 1",
    "photo": Object {
      "2e30-b971-5c62-0b68-837f": Object {
        "url": "https://firebasestorage.googleapis.com/v0/b/...someURL...",
      },
      "38de-15f2-bb7b-b58d-e863": Object {
        "url": "https://firebasestorage.googleapis.com/v0/b/...someURL...",
      },
      "94f2-1494-908f-c17a-5adc": Object {
        "url": "https://firebasestorage.googleapis.com/v0/b/...someURL...",
      },
    },
    "posted": 1562901067,
    "vote": 1,
  },
}

I want to iterate through all the "url" values so I can display all the images. This was my approach so far:

          <FlatList
            refreshing={this.state.refresh}
            onRefresh={this.loadNew}
            data={this.state.photo_feed}
            keyExtractor={(item, index) => index.toString()}
            renderItem={({ item, index }) => (
              <View key={index}>
                <View>
                  <TouchableOpacity>
                    <View>
                    {
                      Object.values(item.photo).map(photoItem => (
                        <Image source={{ uri: photoItem.url }} />
                      )) 
                    }
                    </View>
                  </TouchableOpacity>
                </View>
              </View>

            )}
          />

I am getting this error when running my Object.value function:

TypeError: Object.values requires that input parameter not be null or undefined

回答1:


If you want to iterate over only Photos then you don't need to provide the whole photo_feed object.

You can just supply only the child object containing the photos. Like this,

data={this.state.photo_feed.photo}

After that, the items should render with the same code.



来源:https://stackoverflow.com/questions/57016520/react-native-iterate-through-nested-objects-to-display-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!