【问题标题】:Use functions as useEffect dependencies -> "dependency 'props' missing"使用函数作为 useEffect 依赖项->“缺少依赖项'props'”
【发布时间】:2021-01-26 11:32:32
【问题描述】:

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

考虑以下简单组件:

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

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

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

它在 props 中接收一个函数 calculate 并从中计算 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>;
}

我的问题是:

  • 为什么 linter 不能使用 MyComponent
  • MyComponentVersion2 相比,MyComponent 的语义是否存在差异?

我在codesandbox 中做了一个最小的例子

谢谢!

【问题讨论】:

    标签: reactjs react-hooks use-effect use-state


    【解决方案1】:

    这是因为调用props.calculate(1)props 作为this 值隐式传递给calculate,因此从技术上讲,结果可能取决于整个props 对象(请参阅this React issue)。对于解构的calculate 调用,this 将是未定义的或全局对象,因此不依赖于props

    您可以通过在calculate 的定义中将(x) =&gt; {return x + 1;} 替换为function (x) {console.log(this); return x + 1;} 来查看这两个组件之间的区别。

    【讨论】:

    • 谢谢!这正是我的问题的答案。
    猜你喜欢
    • 2020-12-29
    • 2020-11-22
    • 1970-01-01
    • 2020-03-24
    • 2021-08-19
    • 2022-06-12
    • 2021-02-23
    相关资源
    最近更新 更多