简体   繁体   English

React useEffect 缺少对 function 的依赖?

[英]React useEffect missing dependency for a function?

useEffect(() => {
    calculateTip();
  }, [bill, tipPercentage, numberOfPeople]);

  const calculateTip = () => {
    const tip = ((tipPercentage / 100) * bill).toFixed(2);
    const tipPerGroup = ((tipPercentage / 100) * bill * numberOfPeople).toFixed(
      2
    );
    setTipPerGroup(tipPerGroup);

    setTip(tip);
  };

I get an error:我得到一个错误:

React Hook useEffect has a missing dependency: 'calculateTip'. Either include it or remove the dependency array

Why does useEffect need to have a function in its dependency array?为什么useEffect需要在其依赖数组中有一个 function? I mean the function never changes, it is the same same function, why does React force me to write it inside the dependency array?我的意思是 function 永远不会改变,它是相同的 function,为什么 React 强制我将它写在依赖数组中?

Why does useEffect need to have a function in its dependency array.为什么 useEffect 需要在其依赖数组中有一个 function。 I mean the function never changes.我的意思是 function 永远不会改变。 It is the same same function why does react force me to write it inside the dependency array?它是相同的 function 为什么反应会强制我将它写在依赖数组中?

If that function is defined inside the component then it is not the same function, on the contrary it is re-created on each render.如果 function 是在组件内部定义的,那么它就不是同一个 function,相反,它会在每次渲染时重新创建。 But that is not much related to the reason for the warning.但这与警告的原因没有太大关系。

The reason why that warning asks you to put the function as dependency is the same as for other variables.该警告要求您将 function 作为依赖项的原因与其他变量相同。 The function itself may be referencing some variables which may become stale . function 本身可能正在引用一些可能变得陈旧的变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM