在状态下使用Firestore数据(反应) [英] Using firestore data in state (React)

查看:48
本文介绍了在状态下使用Firestore数据(反应)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何设置要指定的特定Firestore文档字段.每当我尝试运行此字段时,都会收到以下警告.

How do I go about setting a specific firestore document field to state.When ever i try to run this i get the following warning.

(如果有帮助,我正在尝试从Firestore获取数组)

(Im trying to get an array from firestore if that helps)

可能的未承诺的拒绝(ID:0):TypeError:doc.data不是函数.(在"doc.data()"中,"doc.data"未定义)

class Chart extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: []
    };
  }
componentDidMount() {
    db.collection("users")
      .where("email", "==", firebase.auth().currentUser.email)
      .get()
      .then(doc => {
        this.setState({ data: doc.data().prevlevel });
      });
  }
render(){
const data = this.state.data
.....

推荐答案

您要针对集合触发查询.一个查询可以有多个结果,因此返回一个 QuerySnapshot 而不是一个 document .即使只有一个符合您条件的文档,它仍将保留在 QuerySnapshot 中.

You're firing a query against a collection. A query can have multiple results, and thus returns a QuerySnapshot and not a document. Even when there is only one document matching your criteria, it'll still be in a QuerySnapshot.

因此,您的回调将不得不遍历结果.如果您只期望得到一个结果,则可以使用以下方法做到这一点:

So your callback will have to iterate over the results. If you only expect one result, you could do that with:

db.collection("users")
  .where("email", "==", firebase.auth().currentUser.email)
  .get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
      this.setState({ data: doc.data().prevlevel });
    })
  });

这篇关于在状态下使用Firestore数据(反应)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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