Javascript 如何在firestore中添加地图以获取数据?

Javascript 如何在firestore中添加地图以获取数据?,javascript,reactjs,firebase,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Firestore,这是我的订单集合,如何显示订单数组中的所有数据?比如如何映射它,以及如何显示文档ID 这是我在firestore中获取数据的代码: componentDidMount() { firestore .collection("orders") .get() .then((snapshot) => { const orders = []; snapshot.forEach((doc) =>

这是我的订单集合,如何显示订单数组中的所有数据?比如如何映射它,以及如何显示文档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
。每个文档的
order
数组元素中的
documentID
,或者屏幕截图上显示的每个订单文档的文档ID

以下内容将循环遍历
orders
集合中的所有文档,然后,对于每个文档,它将循环遍历每个
orderItem
orderItems
数组的每个元素)。您可以根据自己的具体需要对其进行调整

  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属性。(这回答了您的第一个评论)“如何标记每个数据?”=>您的确切意思是什么?您希望使用哪个数据项作为标签?如labe;它如图所示,带有documentID、productImg和productName