【问题标题】:React-Native: Display/Render multiple images with snapshot.val()React-Native:使用 snapshot.val() 显示/渲染多个图像
【发布时间】:2019-11-21 19:27:39
【问题描述】:

我正在尝试在我的 react-native-app 提要页面中加载多个图像。我已将其存储在我的数据库中,并且能够使用 snapshot.val() 检索数据,但是,我不明白如何在提要屏幕上实际显示/呈现它。

当我做console.log("CONSOLE.LOG --> Snapshot is: ", snapshot.val()) 时,这就是我得到的

CONSOLE.LOG --> Snapshot is:  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,
  },
}

我可以使用这样的平面列表来呈现“作者”、“标题”、“发布”和“投票”:

          <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>
                  <Text>{item.posted}</Text>
                  <Text>{item.author}</Text>
                </View>
                <View>
                    <Image
                      source={{ uri: item.photo }}
                    />
                </View>
                <View>
                  <Text>{item.caption}</Text>
                    <View>
                      <View>
                        <Text>Votes: {item.vote}</Text>
                      </View>
                    </View>
                </View>
              </View>
            )}
          />

但我不明白如何遍历“照片”中的 3 个“网址”

                <View>
                    <Image
                      source={{ uri: item.photo }}
                    />
                </View>

^ 不加载任何图像

【问题讨论】:

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


    【解决方案1】:

    您需要遍历photo 对象的值,并为其中的每个photoItem 创建Image 组件。这样的事情可能会奏效,

    <View>
    {
      Object.values(item.photo).map(photoItem => (
        <Image source={{ uri: photoItem.url }} />
      )) 
    }
    </View>
    

    希望有帮助!

    【讨论】:

    • 您好,您的回答很有道理。但是,当我实施您的解决方案时,我不断收到此错误:TypeError: Object.values 要求输入参数不能为空或未定义。是因为 item.photo 是一个文件夹吗?我怎样才能做到这一点,以便我可以参考“照片唯一 ID”(如上图所示)?谢谢!
    • 所以基本上,我需要像这样遍历嵌套对象:``` Object1 { Object2 { propertyIWantToAcess: anotherpropertyIWantToAcess: } } ```
    • 如前所述,上面的代码将遍历所有照片 url 值并呈现多个 Image 组件。如果您希望访问照片唯一 ID 键而不是 url 值,那么您可以使用 Object.keys(item.photo) 遍历键并获取这些键。
    猜你喜欢
    • 1970-01-01
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2021-10-26
    • 2021-09-12
    相关资源
    最近更新 更多