【问题标题】:NodeJs/Firestore/React- Storing Firestore query results into the stateNodeJs/Firestore/React- 将 Firestore 查询结果存储到状态中
【发布时间】:2019-03-20 12:57:16
【问题描述】:

我有一个名为 user 的类,其中包含用户类所需的所有方法和实例变量。在其中,我有一个方法负责将查询结果返回到 index.js 文件。在这个 index.js 文件中,我希望使用查询中的值设置状态。但这不起作用。

function collectres () {
  var store ='';
  var docRef = db.collection("cities").doc("SF");
  docRef.get()
    .then(function (doc) {
      if (doc.exists) {
        console.log("Document data:", doc.data());
        store = doc.data();// when referenced outside, it doesnt hold anything.
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    })
    .catch(function (error) {
      console.log("Error getting document:", error);
    });
  return store; // returns nothing and seems to not notice the assignment.
}

上面的函数在我的用户类中。从索引中引用时,它看起来像这样。

Random() {
    let a = '';
    a = user.collectres();
    this.setState({name:a});
    console.log(this.state.name);
}

但是,这会将状态设置为先前的值。在查看控制台日志时,我注意到,日志记录的顺序首先从 index.js 控制台.log(this.state.name) 开始,但是我的收集资源的日志不应该首先显示。 任何帮助将不胜感激。

【问题讨论】:

    标签: node.js reactjs google-cloud-firestore


    【解决方案1】:

    数据从 Firestore 异步加载。在加载数据时,您的其余代码将继续执行,然后在数据存在后调用您的 then 回调。

    通过一些放置良好的日志语句最容易看到这一点:

    console.log("Starting to load data");
    docRef.get().then(function (doc) {
      console.log("Got data");
    });
    console.log("Started to load data");
    

    当你运行它时,它会打印:

    开始加载数据

    开始加载数据

    得到数据

    这可能不是您期望的输出,但它完全解释了您所看到的行为。现在您的return storestore = doc.data() 之前运行,这就解释了为什么您没有得到想要的结果。


    这意味着任何需要数据的代码都需要在then() 回调中。因此,如果您将调用 setState() 移动到 store = doc.data() 之后,它将起作用:

    docRef.get().then(function (doc) {
      if (doc.exists) {
        store = doc.data();
        this.setState({name: store});
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    })
    

    或者,您可以从then() 向上返回值。在这种情况下,您的调用代码中也需要then()

    function collectres () {
      var docRef = db.collection("cities").doc("SF");
      return docRef.get()
        .then(function (doc) {
          if (doc.exists) {
            return doc.data();
          } else {
            // doc.data() will be undefined in this case
            console.log("No such document!");
          }
        })
        .catch(function (error) {
          console.log("Error getting document:", error);
        });
    }
    

    然后调用它:

    Random() {
        let a = '';
        user.collectres().then(function(a) {
          this.setState({name:a});
        });
    }
    

    异步 ​​API 在现代编程中极为常见,因此我强烈建议您阅读它们。有关详细信息,请参阅:

    【讨论】:

      猜你喜欢
      • 2021-04-19
      • 2020-04-16
      • 2021-09-11
      • 2020-02-12
      • 1970-01-01
      • 2019-01-11
      • 2018-07-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多