首页 > 解决方案 > 使用函数作为 useEffect 依赖项->“缺少依赖项'props'”

问题描述

我的意图是使用一个函数(由父组件接收,使用创建useCallback)作为依赖项,useEffect并且仅在函数更改时触发该效果。

考虑以下简单组件:

function MyComponent(props) {
  const [myState, setMyState] = useState(0);

  useEffect(() => {
    setMyState(props.calculate(1));
  }, [props.calculate]) 

  return <h1>{myState}</h1>;
}

calculate它在 props 中接收一个函数并myState从中进行计算。但是我得到了 linting 错误:

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

我不明白为什么props.calculate作为依赖项还不够,我们需要props. 我不想使用props,因为这样效果会在每次渲染时重新触发,即使calculate没有改变。(假设calculate已使用useCallback父级创建)。

以下版本不会出现任何 linting 错误:

function MyComponentVersion2(props) {
  const { calculate } = props;
  const [myState, setMyState] = useState(0);

  useEffect(() => {
    setMyState(calculate(1));
  }, [calculate]) 

  return <h1>{myState}</h1>;
}

我的问题是:

我在这个代码框里做了一个最小的例子

谢谢!

标签: reactjsreact-hooksuse-effectuse-state

解决方案


这是因为调用props.calculate(1)隐式地props作为this值传递给calculate,所以从技术上讲,结果可能取决于整个props对象(参见这个 React 问题)。对于解构calculate调用,this将是 undefined 或全局对象,因此不依赖props.

(x) => {return x + 1;}您可以通过替换function (x) {console.log(this); return x + 1;}定义中的来查看两个组件之间的差异calculate


推荐阅读