簡體   English   中英

如何添加 map 以獲取 Firestore 中的數據?

[英]How to add a map in to get the data in the firestore?

這是我的訂單集合,如何顯示訂單數組中的所有數據? 就像我怎樣才能通過 map 它,我怎樣才能顯示文檔 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));
  }

我不完全確定您指的是哪個documentID 每個documentIDorder數組元素中的 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 });
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM