为什么useEffect对不需要放入依赖项数组的字段发出警告?

时间:2020-04-07 19:26:33

标签: reactjs typescript react-hooks

我已经阅读了useEffect文档,但我不明白为什么我会为useEffect中使用的每个变量和函数收到警告,但我并不依赖它们。

在这里考虑我的useEffect

const [updatedComm, setUpdatedComm] = useState<ICommunication>(props.comm)
const [isEditOn, setIsEditOn] = useState<boolean | false>(false)
const getPublishedComm = () => { /* function implementation */ }
const dispatch = useDispatch();

useEffect(() => {
        if (!isEditOn && updatedComm !== props.comm) {
            const publishedComm = getPublishedComm()
            dispatch(editCommunication(publishedComm))
            setCurrentComm(publishedComm)
        }
    }, [isEditOn])

我唯一需要运行此效果的是isEditOn更改时。但是,此代码记录了警告

  Line 66:8:  React Hook useEffect has missing dependencies: 'dispatch', 'getPublishedComm', 'props.comm', and 'updatedComm'. Either include them or remove the dependency array  react-hooks/exhaustive-deps

我该怎么做才能删除这些警告,或者我真的从根本上错过了什么?

请帮助我理解。

谢谢

2 个答案:

答案 0 :(得分:0)

执行此操作以“沉默”该警告,
特别是如果您确定重新渲染应该/应该基于特定的dependencies

useEffect(() => {
   if (!isEditOn && updatedComm !== props.comm) {
      const publishedComm = getPublishedComm();
      dispatch(editCommunication(publishedComm));
      setCurrentComm(publishedComm);
   }
   // eslint-disable-next-line
}, [isEditOn])

但是从我的角度来看,即使updatedComm也应该属于array of dependencies的一部分。
值得了解essence of the array of dependencies的通过跳过效果进行性能优化的方法。

答案 1 :(得分:0)

因为useEffect可以查看状态的使用情况以及状态设置器,所以担心您在回调中有许多更改,但是您使用的依赖项很少。

由于在Functional组件中,函数处理程序也在新的渲染器中更改

您可以做的-提取效果以避免警告

但是强烈建议不要这样做-如果您觉得自己做错了什么,那也许是真的,请再次阅读文档

function editChanged (isEditOn) { // only isEditOn guaranteed to be fresh
   if (!isEditOn && updatedComm !== props.comm) {
      const publishedComm = getPublishedComm();
      dispatch(editCommunication(publishedComm));
      setCurrentComm(publishedComm);
   }
}

useEffect(() => {
   editChanged(isEditOn)
}, [isEditOn])