在数组状态更新后将数据从子级传递到父级,为什么我得到的是前一个状态的实例?

Passing data from child to parent after Array State has been updated, Why am I getting an instance of the prev state?

此功能添加到按钮点击。

  const listChangeHandler = (e) => {
    e.preventDefault();
    setIngredientList((prevArray) => [...prevArray, ingredient]);
    inputIngredient.current.value = "";

    props.data(ingredientList);
  };

问题是: 我在 parent comp 中得到的接收状态 (ingredientList) 是以前的,而不是显示的最新状态在 子组件中

为什么以及解决方法是什么?

正是由于这个事实,state总是在重新渲染后更新,所以当你把它传递给上层组件时,它仍然有它以前的值! 要解决这个问题,您有两个解决方案:

  1. 更新您的代码如下:
const listChangeHandler = (e) => {
    e.preventDefault();
    let temp = [...ingredientList, ingredient];
    setIngredientList(temp);
    inputIngredient.current.value = "";

    props.data(temp);
  };
  1. 使用 useRef 而不是 useState,因为与 state 相比,ref 会立即更新。