NodeJs/Firestore/React-将Firestore查询结果存储到状态 [英] NodeJs/Firestore/React- Storing Firestore query results into the state

查看:43
本文介绍了NodeJs/Firestore/React-将Firestore查询结果存储到状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class called user in which it has all the methods and instnace variables a user class would need. In it, i have a method which is responsible for returning query results to an index.js file. In this index.js file, i was hoping to set the state with the value from the query. But this does not work.

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

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

The function above was within my user class. When referenced from the index, it would look like this.

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

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

however this would set the state with the previous value. When looking at the console log, i have noticed, the order of logging starts first with the index.js console.log(this.state.name),however shouldnt my collect res's log's show first. Any help would be appreciated.

推荐答案

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

Data is loaded from Firestore asynchronously. The rest of your code continues to execute while the data is being loaded, and then your then callback is called once the data is there.

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

It's easiest to see this with a few well-placed log statements:

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

运行此命令时,它将打印:

When you run this it prints:

开始加载数据

开始加载数据

获得数据

这可能不是您期望的输出,但是它完全解释了您所看到的行为.现在,您的 return store store = doc.data()之前运行,这说明了为什么无法获得所需的结果.

This probably isn't the output you expected, but it completely explains the behavior you're seeing. Right now your return store runs before the store = doc.data(), which explains why you're not getting the result you want.

这意味着任何需要数据的代码都必须位于 then()回调内部.因此,如果将调用移到 store = doc.data()之后的紧靠 setState()的地方,它将可以正常工作:

This means that any code that needs the data, needs to be inside the then() callback. So if you move the call to setState() to right after store = doc.data(), it will work:

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():


Alternatively, you can return the value from within the then() upwards. In that case you'll need a then() in your calling code too:

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在现代编程中非常普遍,因此我强烈建议您阅读它们.有关更多信息,请参见:


Asynchronous APIs are extremely common in modern programming, so I highly recommend reading up on them. For more information, see:

这篇关于NodeJs/Firestore/React-将Firestore查询结果存储到状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆