【问题标题】:How can I loop through a collection of data and return the entire object?如何遍历数据集合并返回整个对象?
【发布时间】:2019-08-04 18:43:20
【问题描述】:

我有一个 Firestore 收藏品,我想退回整个物品,但我目前只退回一件物品。我的直觉是,因为我的 resolve 函数在 forEach 中,所以它只返回它看到的最后一个项目,但是当我将它移到 forEach 之外时,我的数据返回 undefined

这是我写的:

 componentDidMount() {
    this.getItemsPromise().then((data) => {
      this.setState({ data: data })
    });
  }

  getItemsPromise() {
    return new Promise((resolve, reject) => {
      this.cancelPromise = reject;
      const db = firebase.firestore();
      db.collection("items").get().then(function(querySnapshot) {
        querySnapshot.forEach(function(doc) {
          const data = [];
          data.push(doc.data())
          resolve(data);
        });
      });
    });
  }

【问题讨论】:

    标签: javascript reactjs google-cloud-firestore


    【解决方案1】:

    试试这个。最好不要将 const 用于可编辑的数组数据。并且您应该将 resolve 放在 forEach 之外,以便在第一个循环中不会触发 resolve。

      getItemsPromise() {
        return new Promise((resolve, reject) => {
          this.cancelPromise = reject;
          const db = firebase.firestore();
          db.collection("items").get().then(function(querySnapshot) {
            let data = [];
            querySnapshot.forEach(function(doc) {
              data.push(doc.data());
            });
            resolve(data);
          });
        });
      }
    

    【讨论】:

    • data 不必坐在then 回调之外。将它放在then 回调中,但在forEach 之外是最有意义的。
    • 它的含义相同,但我会修改它。 :)
    猜你喜欢
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 2021-02-16
    • 2018-08-04
    • 2021-08-22
    • 2021-07-17
    • 1970-01-01
    • 2020-07-21
    相关资源
    最近更新 更多