【问题标题】:Forcing one then() statement to wait for completion of the other强制一个 then() 语句等待另一个完成
【发布时间】:2019-11-04 16:37:44
【问题描述】:

我正在使用 React 并在我的 componentDidMount() 方法中从我的 Firestore 数据库中获取数据。我有两个then() 调用,一个用于当数据库中的数据可用并且我可以保存它时,另一个用于调整状态。

  componentDidMount() {
    db.collection("myCollection")
        .get()
        .then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
                // doc.data() is never undefined for query doc snapshots
                console.log(doc.id, " => ", doc.data().field1);
                allData.push(doc.data());
            })
        })
        .then(
          console.log("Setting State"),
          this.setState({
          isLoaded: true,
          items: allData
        }))
        .catch(function(error) {
            console.log("Error getting documents: ", error);
        });

  }

但是,当我运行该站点时,它会首先尝试设置状态(第二个 then() 语句),而我不希望它这样做,直到保存数据库数据之后。我不确定如何在保存数据库数据后强制进行状态更改。

我尝试过的事情:

1) 将状态更改直接放在函数代码之后,在第一个 then() 中。这给出了错误:

获取文档时出错:TypeError: Cannot read property 'setState' of undefined

【问题讨论】:

  • 您需要从第一个回调中返回一个承诺。如果您不这样做,则无需等待。
  • 除了上述之外,您看到 setState 错误的原因是因为您使用的是function() {} 而不是() => {}。箭头函数维护声明它们的“this”上下文,function() {}s 没有。

标签: javascript reactjs firebase google-cloud-platform google-cloud-firestore


【解决方案1】:

您忘记将设置状态和控制台日志包装在另一个函数中。没有那个,您将向 then 传递两个参数,一个是 console.log 的结果,另一个是 this.setState 的结果。这些是您编写的同步调用。

【讨论】:

    猜你喜欢
    • 2014-10-19
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多