繁体   English   中英

反应 useEffect 和 useCallback linting 错误 - 缺少依赖项

[英]React useEffect and useCallback linting error - missing dependency

即使我在定义它的父组件中使用推荐的 useCallback 钩子,Linter 也抱怨缺少作为依赖项的函数。

有谁知道如何解决这一问题? 似乎无法在任何地方找到示例

此处链接到沙箱https://codesandbox.io/s/hopeful-wind-w4sp5

const arr = ['One', 'Two', 'Three']

const SyncingData = () => {
  const [progress, setProgress] = useState(0)

  const [children, setChildrenProgress] = useState(arr.map(item => 0))

  const handleChildrenProgress = useCallback(
    (progress, index) => {
      setChildrenProgress(
        children.map((item, currIndex) =>
          index === currIndex ? progress : item,
        ),
      )
    },
    [children],
  )

  useEffect(() => {
    setProgress(
      children.reduce((sum, item) => (sum = sum + item), 0) / children.length,
    )
  }, [children])

  return (
    <div>
      <div>Total Progress: {progress}</div>
      <ul>
        {arr.map((item, index) => (
          <Child
            key={index}
            index={index}
            updateProgress={handleChildrenProgress}
            name={item}
            delay={10 * index}
          />
        ))}
      </ul>
    </div>
  )
}

const Child = ({updateProgress, name, index, delay}) => {
  const [progress, setProgress] = useState(0)


  // This is the useEffect the linter doesn't like
  useEffect(() => {
    updateProgress(progress, index)
  }, [progress, index])

  useInterval(() => {
    if (progress < 100) {
      setProgress(progress + 1)
    }
  }, delay)

  return (
    <div>
      {name} {progress}
    </div>
  )
}

我认为您应该尝试在效果的依赖项列表中添加“updateProgress”:

useEffect(() => {
    updateProgress(progress, index)
  }, [progress, index, updateProgress])

函数 updateProgress 包含在您提供的 lambda 中。

linter 试图告诉您,如果该函数发生更改,则效果将不会考虑该更改。

暂无
暂无

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

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