2017-10-14 12 views
1

S'il vous plaît dire, comment mettre en file d'attente retour tableau avec des données. Parce que le rendu de composant plus rapide que firebase envoie des données.Comment obtenir des données d'image asynchrones pour react.js à partir du stockage firebase?

Ce fragment de code de l'action (Redux) de

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

}

Répondre

0

Vous devez attendre des réponses tous les composants logiciels, comme ceci:

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