[英]What's the best way to avoid react-hooks/exhaustive-deps?
I currently use the useEffect hook to run some function or update a variable as an effect of another value/variable being changed我目前使用 useEffect 钩子来运行某个函数或更新一个变量作为另一个值/变量被更改的效果
example:例子:
useEffect(() => {
setValues(types[formStep]]);
}, [formStep]);
I am using the above code to update a variable after another variable has changed, however i keep getting the warning that我正在使用上面的代码在另一个变量更改后更新一个变量,但是我不断收到警告
React Hook useEffect has a missing dependency 'types
and obviosuly when i include 'types' as a dependency, the application falls into a loop and i get the following error很明显,当我将“类型”作为依赖项包含在内时,应用程序会陷入循环,并且出现以下错误
Maximum update depth exceeded.
What is the best way to achieve the variable update but avoid the error?实现变量更新但避免错误的最佳方法是什么? not just for this example for for all cases where you need to update a variable depending on another variable changing before it.
不仅仅是这个例子,适用于您需要根据另一个变量在它之前更改的情况来更新变量的所有情况。
Some solutions found here: https://www.benmvp.com/blog/object-array-dependencies-react-useEffect-hook/ .在这里找到了一些解决方案: https : //www.benmvp.com/blog/object-array-dependencies-react-useEffect-hook/ 。
Another option could be to stringify the dependency so that it is not treated as a different object everytime.另一种选择是对依赖项进行字符串化,以便每次都不会将其视为不同的对象。
useEffect(() => {}, [JSON.stringify(data)])
What is the best way to achieve the variable update but avoid the error?
实现变量更新但避免错误的最佳方法是什么?
It depends on a lot of factors: sometimes using a ref (if you don't want to trigger an update), sometimes you are just deriving state and there is not need for use-effect
(I think that this could be your case), other times you need to trigger an update only when certain value(s) has changed... Sometimes the next value depends on the previous one so you should use the function overload of setState
and avoid passing the previous value as a dependency... There is not a generic answer to this problem.这取决于很多因素:有时使用 ref(如果您不想触发更新),有时您只是在推导状态,不需要
use-effect
(我认为这可能是您的情况) ,其他时候您只需要在某些值发生变化时才需要触发更新......有时下一个值取决于前一个值,因此您应该使用setState
的函数重载并避免将前一个值作为依赖项传递.. . 这个问题没有通用的答案。
It's difficult to know what's happening in your case without more context.如果没有更多背景,很难知道您的案例中发生了什么。 However, I think that I have an idea of what could be happening... This is just a shot in the dark.
但是,我想我知道可能会发生什么......这只是黑暗中的一个镜头。
Is types
an Object that you are defining inside the function of the component? types
是您在组件函数中定义的对象吗? Can you move that definition outside of the function of the component?你能把这个定义移到组件的功能之外吗? Because if you can do that, then there is no need to pass it as a dependency.
因为如果你可以这样做,那么就没有必要将它作为依赖项传递。
Also, do you really need to use useState
and useEffect
for setting values
?另外,你真的需要使用
useState
和useEffect
来设置values
吗? Do you really need to trigger another update?你真的需要触发另一个更新吗? can't you just do this?
你不能这样做吗?
const values = types[formStep];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.