[英]React Js Map function not working on a nested array
我目前正在尝试学习 ReactJS。 对于我的项目,我从 firestore 获取数据,然后想在屏幕上显示。
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"
要检索此数据,我正在使用:
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]);
类别和 Id 很好。 但是当我尝试访问项目时出现问题。 到目前为止,我已经尝试通过索引访问它:
data[0].items[0]
但它只是在控制台中显示undefined
。
尝试在data[0].items
上使用 map 时。 它什么都不做,没有错误,只是不会打印任何细节。
你的问题在这里:
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
运行同步,让您通过在所有的项目快速运行mida
并拉开docRef.get()
承诺,当您去。 但是,对.map
的调用将在任何 Promises 完成之前运行到最后,因此当您尝试在循环运行时将items
推入big
,对get
的调用尚未返回,因此items
不会返回但包含任何东西。
您可以通过将Promise.all
映射到数组中,然后使用Promise.all
等待它们完成,然后使用结果调用Setdata
解决此问题。
像这样的东西(未经测试):
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.