簡體   English   中英

React Native:立即更新 useState?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM