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

时间:2020-02-28 13:44:41

标签: javascript reactjs react-hooks eslint use-effect

Linter抱怨一个函数缺少依赖性,即使我在定义它的父组件中使用推荐的useCallback钩子也是如此。

有人知道如何解决此问题吗?似乎在任何地方都找不到示例

在此处链接到沙箱 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>
  )
}

1 个答案:

答案 0 :(得分:0)

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

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

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

lint试图告诉您,如果该功能发生更改,则效果不会考虑该更改。