简体   繁体   English

useEffect 保持永恒循环

[英]useEffect keeps on eternal loop

I was receiving this warning due to a missing denpendecy on useEffect:由于缺少对 useEffect 的依赖,我收到了此警告:

 useEffect(() => { handleRadioGroup(value) }, [value])

React Hook useEffect has a missing dependency: 'handleRadioGroup'. React Hook useEffect 缺少依赖项:'handleRadioGroup'。 Either include it or remove the dependency array react-hooks/exhaustive-deps包括它或删除依赖数组 react-hooks/exhaustive-deps

So I tried to use a useCallback, to only run the useEffect when this handleRadioGroup function changes.因此,我尝试使用 useCallback,仅在此 handleRadioGroup 函数更改时运行 useEffect。

 const handleRadioSelection = useCallback((value) => { handleRadioGroup(value) }, [handleRadioGroup]) useEffect(() => { handleRadioSelection(value) }, [value, handleRadioSelection])

The problem is that, useEffect runs on enternal loop.问题是, useEffect 在内部循环上运行。 If I print the useCallback function, it shows the same result every time.如果我打印 useCallback 函数,它每次都显示相同的结果。 There is a way to remove this warning, without entering the eternal loop?有没有办法去掉这个警告,不进入永恒循环?

These infinite calls tend to happen because the value of the variable in your dependency array, in your case value or handleRadioSelection , changes within the hook.这些无限调用往往会发生,因为依赖项数组中的变量值(在您的情况下是valuehandleRadioSelection )在钩子内发生了变化。 If this is your case then you'd have to rethink your logic to make sure the values don't change inside of it.如果这是您的情况,那么您必须重新考虑您的逻辑以确保值不会在其中更改。

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

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