问题
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