[英]React Native: Update useState instant?
如何使用useState
即時更新列表? 這是我的代碼,我想立即更新userIngredientsList
以便用戶在其屏幕上立即獲得新的金額。
function handleItemAmount(id) { userIngredientsList.forEach((item) => { if (item.id == id) { item.amount = item.amount + 1 } }) firebase.firestore().doc("ingredients/" + user.uid).update({ ingredients: userIngredientsList }) setUserIngredientsList(userIngredientsList) }
數據庫正在工作,但本地列表沒有。
您可以使用.map()
而不是.forEach()
來創建一個新數組,也可以使用...
賦值來復制每個項目,因為您無法根據 hooks 規則從useState
改變原始數組。
我會嘗試如下:
function handleItemAmount(id) {
const mappedIngredients = userIngredientsList.map(e => ({
...e,
amount: e.id === id ? e.amount + 1 : e.amount
}));
firebase.firestore().doc("ingredients/" + user.uid).update({
ingredients: mappedIngredients
})
setUserIngredientsList(mappedIngredients)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.