【问题标题】:Working with Firestore documents and collection data使用 Firestore 文档和集合数据
【发布时间】:2019-06-21 06:58:30
【问题描述】:

我在 Firestore 中有一些具有以下集合结构的文档

_fl_meta_: Object { createdBy: "Kz5vTvzlmGhRCxqKuDhrvvANqPe2", docId: "76qlSYWItERvJVnLKSDt", env: "production", … }
author: "asd"
content: "last 1"
date: "2019-06-19T12:00:00-07:00"
id: "76qlSYWItERvJVnLKSDt"
imageDeck: Array [ {…} ]
order: 0
parentId: 0
status: "published"
summary: "last 1"
title: "last 1"

我试图遍历我的文档并将其集合数据呈现给我的组件,但我遇到了问题。

我的query

const db = firebase.firestore();
db
  .collection('fl_content')
  .where('_fl_meta_.schema', '==', 'blog')
  .get()
  .then(querySnapshot => {
    querySnapshot.forEach(doc => {
      console.log(doc.data());
      // let results = Object.keys(doc.data()).map(function (key) {
      //   return [String(key), doc.data()[key]];
      // })
      // this.setState({ cards: results });
    });
  })
  .catch(error => {
    console.log("Error getting documents: ", error);
  });

该查询从firestore 输出上述集合。感谢您的帮助

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    获取您的querySnapshot 并将其映射为包含您的文档的对象数组。

    const querySnapshot = firebase.firestore().collection('fl_content')
      .where('_fl_meta_.schema', '==', 'blog').get()
    
    .then((querySnapshot) => {
      // The following line will result in an array of objects (each object is your document data)
      const yourDocuments = querySnapshot.docs.map((doc) => doc.data());
      this.setState({cards: yourDocuments});
    })
    .catch((error) => {
      console.log(error);
    });
    

    然后你可以这样做:

    // INSIDE YOUR RENDER METHOD
    
    const cardItems = this.state.cards.map((item,index) => 
      <CardComponent key={index}>
         {item.name} // Here you can access and display the fields of your documents
      </CardComponent>
    );
    
    return(
      <SomeContainerComponent>
         {cardItems}
      </SomeContainerComponent>
    );
    

    【讨论】:

    • 你能向我解释一下它是如何工作的吗,对所有这些反应东西来说仍然是新的,让我很困惑,你需要创建一个 const 来存储/加载一个组件,以便在另一个组件中呈现它组件....大声笑...
    • 那个cardItems 变量正在存储一个包含&lt;CardComponent/&gt;'s 的数组。那就是 JSX 标记,该数组的每个元素都被翻译成这样的东西:例如,return(&lt;div&gt;aaa&lt;/div&gt;); 被翻译成 return React.createElement("div", null, "aaa");,它基本上在屏幕上创建并呈现它。这将发生在数组cardItems 的每个元素上,因此所有元素都将相应地呈现。看看Introducing JSX from React DOCS
    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2020-02-27
    • 2020-08-01
    • 2021-10-12
    • 1970-01-01
    • 2021-04-18
    • 2019-11-13
    • 1970-01-01
    相关资源
    最近更新 更多