从Firestore提取数据

Gab*_*nus 2 firebase reactjs google-cloud-firestore

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

此代码有效:

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

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

...
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>
);
}
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Dac*_*nny 5

您的呈现逻辑将需要说明对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 }) 
      });

    });
}
Run Code Online (Sandbox Code Playgroud)

接下来,添加componentDidMount()到您的组件,然后getMyStory()像这样添加调用:

componentDidMount() {

    /* Cause your component to request data from Firebase when
       component first mounted */
    this.getMyStory()
}
Run Code Online (Sandbox Code Playgroud)

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

  render () {

    return (<p>{ this.state.items || 'Loading' }</p>);
 }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!