【问题标题】:useState is not updating inside array.map(). ReactJSuseState 没有在 array.map() 中更新。反应JS
【发布时间】:2021-07-22 10:31:05
【问题描述】:

我正在尝试通过在 array.map 中使用 useState 添加数组的值,但值没有更新

function App() {
  const [ingredients, setIngredients] = useState([]);
  
  const getIngredients = (data) => {
    data.map((item, i) => {
      console.log(data[i]);
      setIngredients([...ingredients, data[i]]);
     // setIngredients([...ingredients, item]); <- Also doesnt work 
      console.log(ingredients);
    });

Console.log(数据)

(26) ["Product", "Information↵NUTELLA", "HAZELNUT", "SPREAD", "↵Total:", "↵aty:", "↵BARILLA", "SPAGHETTI", "Z↵Total:", "↵CLASSICO", "CRMY", "ALFERO", "DI", "ROMA", "PENNE", "RIGATE", "PASTA", "↵Order", "Summary↵item", "Subtotat", "↵Sales", "Tax", "Total:", "", "↵", Array(0)]

console.log(成分);

[]

console.log(items);

Lists out all the items one after the other

【问题讨论】:

    标签: arrays reactjs use-state


    【解决方案1】:

    setState 是异步的,所以它不能保证更新之前的状态,所以传递一个函数给 setState 让它工作。

    setIngredients((ingredients) => [...ingredients, data[i]]);
    

    【讨论】:

    • 我不知道 setState 是异步的。您的解决方案有效,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-07-17
    • 2021-08-05
    • 1970-01-01
    • 2022-12-06
    • 2020-10-28
    • 2021-04-17
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多