React Native中的Firebase Firestore集合检索

时间:2017-10-08 14:44:54

标签: firebase react-native expo google-cloud-firestore

我正在使用Firebase web api构建一个带有Expo的React Native应用程序,并尝试从我的Firestore项目中检索一组文档。根据{{​​3}}上的文档,我应该能够使用集合快照提供的forEach()方法迭代集合,如下所示:

db
.collection('services')
.get()
.then(snapshot => {
  snapshot.forEach(doc => {
    if (doc && doc.exists) {
      console.log(doc.id, ' => ', doc.data());
    }
  });
});

然而,这只记录了一个文件,尽管我目前在该系列中有3个文件,但我缺少什么?请帮忙。

我的firebase配置如下:

import * as firebase from 'firebase';
 firebase.initializeApp({
    "projectId": "my-project-id",
    "apiKey": "my-api-key",
    "authDomain": "my-project.firebaseapp.com",
    "databaseURL": "https://my-project.firebaseio.com",
    "storageBucket": "my-project-id.appspot.com/",
    "messagingSenderId": "my-messaging-sender-id"
})
const db = firebase.firestore();

3 个答案:

答案 0 :(得分:2)

嘿,从Firestore检索数据是一个说明和一个有效的摘录/应用示例。

该示例在Reactjs和React Native上均可使用,但是我不能共享属于客户的RN示例。

说明:

•?使用firestore时,您必须将Array-Like值转换为真实值,这可以通过forEach((doc)=> {} = doc.data();}

完成)

•然后使用push()方法将值附加到Array中。

•之后,您可以使用setState定义与状态链接的dataSource。

•,然后您可以将数据呈现到UI上。

这是我创建的一个演示React应用程序项目,该项目可从Cloud Firestore推送和提取数据以及下面的工作组件片段示例。

源代码:https://github.com/trackmystories/Checkout-challenge

视频示例:https://drive.google.com/file/d/1XAGjyJU-QiuolNmtUVyjg9tQAloeyABj/view?usp=sharing

import React, {Component} from 'react'
import "firebase/firestore"
import * as firebase from 'firebase';
import { firebaseConfig } from '../api/config'



export default class CommentsTab extends Component {

  constructor(props) {
  super(props);
  if (!firebase.apps.length) {
  firebase.initializeApp(firebaseConfig);
  }
  this.ref = firebase.firestore().collection('Comment').orderBy('date', 'desc').limit(10);
  this.state={
  dataSource : []
}
}

componentDidMount(){
  this.unsubscribe = this.ref.onSnapshot(this.latestComments);
}



latestComments = (commentsSnapShot) =>{
  const Comment = [];
  commentsSnapShot.forEach((doc) => {
  const {name, email, date, comment} = doc.data();
    Comment.push({
      key: doc.id,
      name,
      email,
      date,
      comment
    });
  });
  this.setState({
    dataSource : Comment,
  });
}




  render(){
     const {dataSource} = this.state
    return(

    )
  }
}

答案 1 :(得分:1)

我经过一些调试后终于得到了它。看起来我需要做的是在querySnapshot上的forEach返回的每个快照上使用_document.data属性。所以我的代码现在看起来像这样:

db
    .collection('services')
    .get()
    .then(snapshot => {
      snapshot
        .docs
        .forEach(doc => {
          console.log(JSON.parse(doc._document.data.toString()))
        });
    });

这感觉有点像黑客但只记录doc._document.data会返回大量元数据以及每个文档,toString()只返回文档数据,但作为JSON字符串,然后我将其解析为JavaScript使用JSON.parse的对象。

答案 2 :(得分:0)

另外,您还可以使用像firestorter这样的lib将Firestore无缝集成到React

https://medium.com/@hrutjes/building-a-react-firestore-app-with-zero-effort-and-mobx-525df611eabf

相关问题