简体   繁体   English

React Js Map 函数不适用于嵌套数组

[英]React Js Map function not working on a nested array

I am currently trying to learn ReactJS.我目前正在尝试学习 ReactJS。 For my projects I am getting data from firestore and then want to display on the screen.对于我的项目,我从 firestore 获取数据,然后想在屏幕上显示。

Data in Firestore is stored as : Firestore 中的数据存储为:

category: "Lemon"
currentUser:
  createdAt: October 21, 2020 at 2:52:25 PM UTC+5:30
  displayName: null
  email: "email@ymail.com"
id: "123"
dish: "vs"
image: "imageurl"
price: "8"

To retrieve this data I am using:要检索此数据,我正在使用:

useEffect(() => {
  let m = [];
  var docRef = firestore.collection("Dish");
  docRef.get().then(function (querySnapshot) {
    querySnapshot.forEach(function (doc) {
      m.push({
        id: doc.id,
        category: doc.data().category,
      });
    });

    Setmida(m);

    Setmid(false);

    if (mid === false) {
      let big = [];
      mida.map((f) => {
        let items = [];
        var docRef = firestore
          .collection("Dish")
          .where("category", "==", "Lemon");
        docRef.get().then(function (querySnapshot) {
          querySnapshot.forEach(function (doc) {
            items.push({
              dish: doc.data().dish,
            });
          });
        });

        big.push({
          id: f.id,
          category: f.category,
          items,
        });
      });

      Setdata(big);

      Setload(false);
    }
  });
}, [mid]);

Category and Id are well.类别和 Id 很好。 But the problem arises when I try to access items.但是当我尝试访问项目时出现问题。 So far I have tried to access it by index:到目前为止,我已经尝试通过索引访问它:

data[0].items[0]

But it just shows undefined in console.但它只是在控制台中显示undefined

When trying to use map on the data[0].items .尝试在data[0].items上使用 map 时。 It just doesn't do anything, no errors, it just won't print any details.它什么都不做,没有错误,只是不会打印任何细节。

Your problem is here:你的问题在这里:

  mida.map((f) => {
        let items = [];
        var docRef = firestore
          .collection("Dish")
          .where("category", "==", "Lemon");
        docRef.get().then(function (querySnapshot) {
          querySnapshot.forEach(function (doc) {
            items.push({
              dish: doc.data().dish,
            });
          });
        });

        big.push({
          id: f.id,
          category: f.category,
          items,
        });

Array.map runs synchronously, so you are running quickly through all the items in mida and kicking off the docRef.get() Promises as you go. Array.map运行同步,让您通过在所有的项目快速运行mida并拉开docRef.get()承诺,当您去。 However, the call to .map will run to the end before any of the Promises have completed, so when you try to push items in to big as the loop is running, the calls to get haven't returned and so items doesn't yet contain anything.但是,对.map的调用将在任何 Promises 完成之前运行到最后,因此当您尝试在循环运行时将items推入big ,对get的调用尚未返回,因此items不会返回但包含任何东西。

You could fix this by mapping your Promises in to an array and then using Promise.all to wait for them to complete, then calling Setdata with the result.您可以通过将Promise.all映射到数组中,然后使用Promise.all等待它们完成,然后使用结果调用Setdata解决此问题。

Something like this (untested):像这样的东西(未经测试):

 if (mid === false) {
      let big = []
      Promise.all(
        mida.map(f => {
          let items = []
          var docRef = firestore
            .collection('Dish')
            .where('category', '==', 'Lemon')
          return docRef.get().then(function(querySnapshot) {
            querySnapshot.forEach(function(doc) {
              items.push({
                dish: doc.data().dish,
              })
            })
            return { id: f.id, category: f.category, items }
          })
        }),
      ).then(results => {
        Setdata(results)
        Setload(false)
      })
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM