简体   繁体   English

React Native:立即更新 useState?

[英]React Native: Update useState instant?

How can I update a List with useState instant?如何使用useState即时更新列表? Here is my code I want to update the userIngredientsList instant so the user gets the new amount instant on his screen.这是我的代码,我想立即更新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) }

The database is working, but the local list isn't.数据库正在工作,但本地列表没有。

You can use .map() instead of .forEach() to create a new array, also you can use ... assignment to copy each items because you cannot mutate the original array from useState based on the hooks rule.您可以使用.map()而不是.forEach()来创建一个新数组,也可以使用...赋值来复制每个项目,因为您无法根据 hooks 规则从useState改变原始数组。

I would try as the following:我会尝试如下:

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