react-native firebase,firesrore,当getdownloadURL时,如何存储数据?

时间:2019-04-30 01:03:15

标签: react-native

我正在尝试将URL存储在getdownloadURL中。并希望在渲染功能中使用它。 但无论我做什么,(据我所知)uri都是空的。你能帮我吗?

querySnapshot.forEach((doc) => {
            const { ID, TIME,STAR,PHOTO,UID,COMMENT } = doc.data();
            const ref = firebase.storage().ref(PHOTO);

            ref.getDownloadURL().then(url => {
              this.setState({ uri: url })
             });

           // console.log(PHOTO);
            todos.push({
              key: doc.id,
              doc, // DocumentSnapshot
              ID,
              TIME,
              STAR,
              uri,
              PHOTO,
              UID,
              COMMENT
            });


          });
          this.setState({ 
            todos

         });

2 个答案:

答案 0 :(得分:0)

由于db调用ref将花费一些时间,因此Javascript将继续执行代码并在db调用完成之前运行todos.push({[your variables]},因此uri将为空。函数“异步”并等待数据库调用,看看是否适合您。

            const { ID, TIME,STAR,PHOTO,UID,COMMENT } = doc.data();
            const ref = firebase.storage().ref(PHOTO);

             await ref.getDownloadURL().then(url => {
              this.setState({ uri: url })
             });

           // console.log(PHOTO);
            todos.push({
              key: doc.id,
              doc, // DocumentSnapshot
              ID,
              TIME,
              STAR,
              uri,
              PHOTO,
              UID,
              COMMENT
            });


          });
          this.setState({ 
            todos

         });

答案 1 :(得分:0)

我自己解决这个问题。 解决方案是在getdownloadURL和setstate中推送数组。 代码在这里

 ref.getDownloadURL().then(url => { // have a img
          // this.setState({ uri: url });
          todos.push({
            key: doc.id,
            doc, // DocumentSnapshot
            ID,
            TIME,
            STAR,
            uri : url,
            PHOTO,
            UID,
            COMMENT
          });
            this.setState({ 
              todos  
            });