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

此代码有效:

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


这行不通。 (它可以编译,但是不返回任何内容):

...
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来解决此问题:

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()中,如下所示:

componentDidMount() {

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


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

  render () {

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


希望这可以帮助!

10-06 15:18