【发布时间】:2021-06-29 06:11:05
【问题描述】:
下面的 sn-p 表示数据库的侦听器,它在更改时返回多个对象(每个对象代表一个文档)然后它将获得id 和quantity该对象然后它将遍历每个对象并将object.price元素添加到每个对象并再次调用数据库然后它将使用quantity和object.price元素来获取每个对象的总量但是问题是quantity 和id 没有按预期为每个对象更新,而不是quantity 值将始终是最后一个对象quantity 的值。
但是当我尝试在forEach() 中获取id 和quantity 的值时,但是一旦在调用数据库的函数内部和在它外部,如下面的sn-p 所示,问题正在发生仅在函数内部,当尝试在函数之后获取quantity 值时会出现相同的问题(我将在 sn-p 之后将已登录的内容的副本放在控制台中)
useEffect(() => {
db.collection("users").doc("4sfrRMB5ROMxXDvmVdwL").collection("basket").onSnapshot((docs) => {
const oneSubTotal = [];
let array = []
let object = undefined;
let id = undefined;
let quantity = undefined;
docs.forEach( doc =>{
object = doc.data()
id = object.id;
quantity = object.quantity
console.log( " the quantity before is " + quantity)
console.log(" the id before is " + object.id)
db.collection("products").doc(id).get().then( (e)=>{
object.price = (e.data().price);
console.log( " the quantity inside is " + quantity)
console.log(" the id inside is " + id)
oneSubTotal.push(object.price * quantity)
})
console.log( " the quantity after is " + quantity)
console.log(" the id after is " + id)
})
});
}, [])
这是控制台中记录的内容
the quantity before is 9
the id before is 1
the quantity before is 10
the id before is 2
the quantity inside is 10
the id after is 2
the quantity inside is 10
the id after is 2
the quantity after is 10
the id after is 2
the quantity after is 10
the id after is 2
【问题讨论】:
标签: javascript reactjs firebase google-cloud-firestore async-await