useState 不在 array.map() 内更新。 ReactJS

时间:2021-04-29 04:01:55

标签: arrays reactjs use-state

我正在尝试通过在 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(ingredients);

<块引用>

[]

console.log(items);

Lists out all the items one after the other

1 个答案:

答案 0 :(得分:2)

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

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