javascript - 如何从 Firebase 存储获取 React.js 的异步图像数据?

标签 javascript reactjs firebase asynchronous firebase-realtime-database

请告诉我,如何将数据放入队列返回数组中。因为组件渲染速度比 firebase 发送数据更快。

此代码片段来自操作(redux)

function fetchPosts(key) {
return dispatch => {
    dispatch(requestPosts(key))
    return database.ref('article/').once('value', snap => {
        let childData = []
        snap.forEach(function(child) {
            getImage(child.val().thumb).then((url) => {
                console.log(url)
                return {
                    "id": child.key,
                    "url": url,
                    ...child.val()
                }
            }).then((array) => {
                console.log(array)
                childData.push(array)
            })
        })
        dispatch(receivePosts(key, childData))
    })
    .catch((error) => {
      console.log(error)
      dispatch(receivePosts(error))
    })
}

}

最佳答案

您需要等待所有快照响应,如下所示:

// Boilerplate start ---

function getImage(thumb) {
  return new Promise((resolve) => {
    setTimeout(() => resolve(thumb + ' url'), Math.random() * 500);
  });
}

function Child(key, value) {
  this.key = key;
  this.value = value;
}

Child.prototype.val = function () {
  return this.value;
}

function receivePosts(key, childData) {
  return {key, childData};
}

function dispatch(action) {
  console.log(action);
}

snap = [
  new Child('key1', {thumb: 'thumb1'}), 
  new Child('key2', {thumb: 'thumb2'}), 
  new Child('key3', {thumb: 'thumb3'}),
  new Child('key4', {thumb: 'thumb4'}),
  new Child('key5', {thumb: 'thumb5'}),
  new Child('key6', {thumb: 'thumb6'}),
  new Child('key7', {thumb: 'thumb7'}),
  new Child('key8', {thumb: 'thumb8'})
];

// Boilerplate end ---

function insideDatabaseRefOnce(key) {
  return Promise.all(snap.map(function(child) {
    return getImage(child.val().thumb).then((url) => {
      return {
        "id": child.key,
        "url": url,
        ...child.val()
      }
    });
  })).then((childData) => {
    dispatch(receivePosts(key, childData))
  });
}

insideDatabaseRefOnce('The key');

关于javascript - 如何从 Firebase 存储获取 React.js 的异步图像数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46749515/

相关文章:

javascript - 如何在 for 循环中使用 .each of jquery 一次突出显示一个标签

javascript - 断言 `this.props.children` 中仅传递单个子项

ios - Swift Firebase 按距离排序

Firebase 远程配置与 A/B 测试功能

android - Firebase 中的后台通知 : Android Oreo

javascript - 简单数据的最佳服务端数据存储方式

javascript - 在 XMLHttpRequest 之后打开页面

reactjs - React Navigation v3 与 React Native Navigation v2

javascript - jQuery : Sending multiple files and parameters got Error: Dropzone already attached

javascript - Reactjs 将键盘语言自动更改为波斯语