React Native:遍历嵌套对象以显示值

时间:2019-07-13 05:46:28

标签: arrays firebase react-native firebase-realtime-database react-native-flatlist

我想在屏幕上显示多个图像。我的数据库树如下所示:

我还能够通过snapshot.val()加载对象,这是运行时在控制台中的样子:

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,
  },
}

我想遍历所有“ url”值,以便可以显示所有图像。 到目前为止,这是我的方法:

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

            )}
          />

运行Object.value函数时出现此错误:

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

1 个答案:

答案 0 :(得分:0)

如果只想遍历照片,则无需提供整个photo_feed对象。

您只能提供包含照片的子对象。像这样

data={this.state.photo_feed.photo}

之后,这些项目应使用相同的代码呈现。

相关问题