【问题标题】:How to add a map in to get the data in the firestore?如何添加地图以获取 Firestore 中的数据?
【发布时间】:2021-04-04 13:20:02
【问题描述】:

这是我的订单集合,如何显示订单数组中的所有数据?比如如何映射它以及如何显示文档 ID?

这是我在 firestore 中获取数据的代码:

  componentDidMount() {
    firestore
      .collection("orders")
      .get()
      .then((snapshot) => {
        const orders = [];
        snapshot.forEach((doc) => {
          const data = doc.data();
          users.push({
            ...orders
          });
        });
        this.setState({ users: users });
        // console.log(snapshot)
      })
      .catch((error) => console.log(error));
  }

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    我不完全确定您指的是哪个documentID。每个文档的order 数组元素中的documentID 还是每个订单文档的文档ID,如屏幕截图所示?

    下面将循环遍历orders 集合中的所有文档,然后,对于每个文档,它将遍历每个orderItemorderItems 数组的每个元素)。您可以对其进行调整以满足您的确切需求。

      firestore
        .collection('orders')
        .get()
        .then((snapshot) => {
          const orders = [];
          snapshot.forEach((doc) => {
    
            // Update following your comment
            // If you want to get the ID of the order document, do as follows
            const orderDocID = doc.id;            
    
            const data = doc.data();
            data.order.orderItems.forEach((item) => {
              orders.push(item.documentID);
            });
          });
          this.setState({ orders: orders });
        });
    

    如果您想为订单项添加更多数据(根据您上次的评论),请执行以下操作:

      firestore
        .collection('orders')
        .get()
        .then((snapshot) => {
          const orders = [];
          snapshot.forEach((doc) => {
            const orderDocID = doc.id;            
            const data = doc.data();
            data.order.orderItems.forEach((item) => {
              const orderObj = {
                  documentID: item.documentID,
                  productImg: item.productImg,
                  productName: item.productName,
              }
              orders.push(orderObj);
            });
          });
          this.setState({ orders: orders });
        });
    

    【讨论】:

    • 谢谢。我会试试这个。我指的是那个文档 ID,位于最顶部的那个。
    • 比你,它确实有效。我已经可以映射它并显示在屏幕上。如何标记每个数据?这就是我映射它的方式: {this.state.orders.map((item, i) => (
    • {item}
    • ))}
  • 查看更新。您需要使用 id 属性。 (这回答了您的第一条评论)
  • "如何标记每个数据?" => 你到底是什么意思?您想将哪个数据项用作标签?
  • 喜欢拉贝;如图所示,带有 documentID、productImg 和 productName
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签