【问题标题】:How get async image data for react.js from firebase storage?如何从 firebase 存储中获取 react.js 的异步图像数据?
【发布时间】:2017-10-15 09:25:54
【问题描述】:

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

这个来自action(redux's)的代码片段

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

}

【问题讨论】:

    标签: javascript reactjs firebase asynchronous firebase-realtime-database


    【解决方案1】:

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

    // 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');

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2020-06-01
      • 2019-10-15
      • 2021-02-14
      • 2020-06-26
      相关资源
      最近更新 更多