从Firestore提取数据 [英] Fetching data from Firestore

查看:76
本文介绍了从Firestore提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我尝试从Firestore中获取数据,当我对其进行控制台日志记录时,我将集合的内容取回,但是当我将代码移至某个函数时,便无法将其返回.

So I am trying to fetch data from Firestore, when I console log it I got the content of my collection back, but when I move the code to a function I am not able to return it back.

此代码有效:

const db = firebase.firestore();
db.settings({ timestampsInSnapshots: true});
db.collection('story').get().then((snapshot) => {
snapshot.docs.forEach(doc => {console.log(doc.data())
    ;})
})

这不起作用. (它可以编译,但不返回任何内容):

This doesnt work. (it compiles, but doesn`t return anything):

...
getMyStory = () => {
        const db = firebase.firestore();
        db.settings({ timestampsInSnapshots: true});
        db.collection('story').get().then((snapshot) => {
        snapshot.docs.forEach(doc => {
            let items = doc.data();
        })
        });
        return this.items;
    }


    render () {


        return (
        <p>{this.getMyStory}</p>
);
}

我在做什么错了?

推荐答案

您的呈现逻辑将需要考虑对Firebase的查询是异步的.考虑通过对代码进行以下调整,利用组件state来解决此问题:

Your rendering logic will need to account for the query to Firebase being asynchronous. Consider making use of your components state to resolve this, by making the following adjustments to your code:

getMyStory() { /* Remove arrow function */

    const db = firebase.firestore();
    db.settings({ timestampsInSnapshots: true});
    db.collection('story').get().then((snapshot) => {

      snapshot.docs.forEach(doc => {
          let items = doc.data();

          /* Make data suitable for rendering */
          items = JSON.stringify(items);

          /* Update the components state with query result */
          this.setState({ items : items }) 
      });

    });
}

接下来,将componentDidMount()添加到您的组件中,然后将调用添加到getMyStory()中,如下所示:

Next, add componentDidMount() to your component, and then add the call to getMyStory() like so:

componentDidMount() {

    /* Cause your component to request data from Firebase when
       component first mounted */
    this.getMyStory()
}

最后,更新您的渲染方法以使用状态,而不是方法:

Finall, update your render method to use the state, rather than method:

  render () {

    return (<p>{ this.state.items || 'Loading' }</p>);
 }

希望这会有所帮助!

这篇关于从Firestore提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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