but the issue is the value of Total when the page renders first time always will be the total price of the first item which is represented with the first object in the items array and when I modify the quantity of any item (without refreshing the page) the Total value shows the correct amount for few seconds then the value of it returns to show the first items total price only推荐答案在您的 onSnapshot 处理程序中,您正在调用 console.log(array)和 setItems(数组)过早.这有可能导致您的应用多次渲染.您应该确保在 forEach 循环之外调用这些行.In your onSnapshot handler, you are calling console.log(array) and setItems(array) prematurely. This potentially causes your app to be rendered multiple times. You should make sure to be calling these lines outside of the forEach loop..onSnapshot((docs) => { let array = [] docs.forEach(doc => { array.push(doc.data()) }); console.log(array) setItems(array)});但是,即使这样,在调用 setItems 之前获取商品价格会更有效.另外,您应该使用 forEach 来逐一调用数据库./3068190>此答案,可以作为实用工具功能使用, fetchDocumentsWithId() .But even so, it would be more efficient to fetch the item prices before calling setItems. Plus, instead of calling out to the database one-by-one using forEach, you should bundle the requests into batches like shown in this answer which is available as a utility function, fetchDocumentsWithId()..onSnapshot((docs) => { const cartItems = [], itemPriceObject = {}; // cartItems will be ({ id: string, quantity: number, price: number | null, lineTotal: number })[] // itemPriceObject will be a map of IDs to their price (a Record<string, number | null>) (used to deduplicate IDs & store prices) docs.forEach(doc => { const cartItem = doc.data() cartItems.push(cartItem) itemPriceObject[cartItem.id] = null }); // idsArray is a deduplicated list of IDs const idsArray = Object.keys(itemPriceObject); fetchDocumentsWithId( db.collection("products"), idsArray, (itemDoc) => { itemPriceObject[itemDoc.id] = itemDoc.get("price") // more efficient than itemDoc.data().price } ) .then(() => { // if here, all prices (that are available) have been retrieved // MAY BE NULL! Consider these items to be "not available" const totalSum = 0 // put prices in their items, calculate line cost and add to total cartItems.forEach(item => { item.price = itemPriceObject[item.id] item.lineTotal = item.price === null ? 0 : item.price * item.quantity totalSum += item.lineTotal } // set items & total sum setItems(cartItems) setTotal(totalSum) }) .catch((error) => { // failed to retrieve some documents from the database // TODO: update UI });}); 注意:为清楚起见, subTotal (意味着:一些值的总和,但不是所有值的总和)被重命名为 lineTotal (意味着:此条目/行中的项目成本,即成本x数量)Note: For clarity, subTotal (meaning: the sum of some, but not all values) was renamed to lineTotal (meaning: the cost of items in this entry/line, the cost x quantity) 这篇关于数据库(firestore)调用仅采用第一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!