函数钩子使用中无限循环的问题

时间:2019-05-15 18:15:56

标签: javascript reactjs react-hooks

我在钩子上遇到无限循环的问题, 我正在传递本地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

2 个答案:

答案 0 :(得分:1)

useEffect的第二个参数是要监视的状态/钩子数组,当状态/钩子发生变化时,就会运行效果。由于您的breakfast是常量,因此我猜您只是希望原始的stateProductbreakfast。因此,不要使用[]作为默认值,而是使用breakfast

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

另外,在您的react功能组件之外声明const breakfast ...可能是一个好主意,这样它就不会在每次重新渲染时都重新声明它。

答案 1 :(得分:1)

问题很简单,您拥有breakfast数组作为对useEffect的依赖关系,并且在useEffect中设置了早餐数组本身。现在,由于在组件内部声明了const breakfast数组,因此每次都会生成对其的新引用,并且由于useEffect将数组设置为状态,因此它会重新渲染,并且在下一次重新渲染breakfast数组时,比较会失败,因为参考已更改。

解决方案很简单,您不需要在组件中包含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;
相关问题