函数挂钩useEffect中的无限循环问题

problem with infinite loop in function hook useEffect

我的钩子上有一个无限循环的问题, 我正在传递本地 JSON 早餐的数据。如果您正在迭代映射数据,我将用它来绘制按钮菜单。 如果我删除函数末尾的数据,并保留空数组,它会向我发送以下错误:

const BreakfastComponent = () => {

   const breakfast = [
    {
      id: 0,
      name: "Sandwich de jamón y queso",
      price: '35',
      img: "https://i.ibb.co/ynC9xHZ/sandjc.png",

    },
    {
      id: 1,
      name: "Jugo Natural",
      price: '15',
      img: "https://i.ibb.co/8mrd4MK/orangejuice.png",
    },
    {
      id: 2,
      name: "Café americano",
      price: '20',
      img: "https://i.ibb.co/nsj1GL0/americancoffe.png",
    },
    {
      id: 3,
      name: "Café con leche",
      price: '28',
      img: "https://i.ibb.co/GRPBm7j/coffeandmilk.png",
    }
  ];


  const [stateProduct, setStateProduct] = useState([ ]);


  useEffect(() => {

    setStateProduct(breakfast);
  }, [breakfast]);

  return (

      <section className="databreakfast">
        {stateProduct.map((element, item) =>
          <ButtonsBComponent
            key={item}
            {...element}

          />
        )}
        </section>



  )
};

export default BreakfastComponent;

React Hook useEffect 缺少依赖项:'breakfast'。包括它或删除依赖数组 react-hooks/exhaustive-deps

useEffect的第二个参数是一个state/hooks的数组,当它们发生变化时,会产生运行的效果。因为你的 breakfast 是一个常量,我猜你只是想让原来的 stateProduct 变成 breakfast。因此,不要使用 [] 作为默认值,而是使用 breakfast.

const [stateProduct, setStateProduct] = useState(breakfast);

此外,在你的 React 功能组件之外声明 const breakfast ... 可能是个好主意,这样它就不会 re-declare 每个 re-render.

问题很简单,您有 breakfast 数组作为 useEffect 的依赖项,并且在 useEffect 中您正在设置早餐数组本身。现在,由于 const breakfast 数组是在组件内部声明的,因此每次都会生成对它的新引用,并且由于 useEffect 将数组设置为状态,它 re-renders 和下一个 re-render [=11= 的比较] 数组失败,因为引用已更改。

解决方法很简单,组件中不需要const数组,也不需要使用useEffect

const breakfast = [
    {
      id: 0,
      name: "Sandwich de jamón y queso",
      price: '35',
      img: "https://i.ibb.co/ynC9xHZ/sandjc.png",

    },
    {
      id: 1,
      name: "Jugo Natural",
      price: '15',
      img: "https://i.ibb.co/8mrd4MK/orangejuice.png",
    },
    {
      id: 2,
      name: "Café americano",
      price: '20',
      img: "https://i.ibb.co/nsj1GL0/americancoffe.png",
    },
    {
      id: 3,
      name: "Café con leche",
      price: '28',
      img: "https://i.ibb.co/GRPBm7j/coffeandmilk.png",
    }
  ];

const BreakfastComponent = () => {

  const [stateProduct, setStateProduct] = useState(breakfast);


  return (

      <section className="databreakfast">
        {stateProduct.map((element, item) =>
          <ButtonsBComponent
            key={item}
            {...element}

          />
        )}
        </section>



  )
};

export default BreakfastComponent;