我可以使用“UseEffect"吗?只有一定的价值? [英] Can I use a "UseEffect" only with a certain value?

查看:46
本文介绍了我可以使用“UseEffect"吗?只有一定的价值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试使用 React 钩子的 UseEffect,我知道我可以添加可以在更改时激活它的变量,但我想知道是否有办法仅在值满足某些条件时激活 useEffect.

Hello I am trying to use a UseEffect of react hooks, I know I can add variables that on change can activate it, but I would like to know if there is a way to activate the useEffect only when the value meets certain criteria.

我已经在 useEffect 中创建了一个条件,并且我知道它可以工作,但我想知道是否还有其他方法可以做到.

I have already created a conditional inside the useEffect and I know it works, but I would like to know if there's another way to do it.

useEffect(() => {
  doSomething();
  if(!isOpen)
   doSomething2();
}, [isOpen, otherThing]); 

在上面的示例中,我希望 doSomething2 仅在其值为 false 时才起作用.

In the example above I want doSomething2 to work only when its value is false.

本示例中的 isOpen 具有默认值 false,然后当它从数据库中检索某些内容时它会变为 true,最后当它完成获取时它又会返回 false.

isOpen in this examample has a default value of false, then when it retrieves something from the database it turns into true and finally when it finished fetching it goes back to false.

我希望钩子仅在值从 true 切换到 false 时激活,而不是在每次更改时激活.

I expect the hook to activate only when the value switches from true to false and not in every change.

有没有办法做到这一点?

Is there a way to do that?

推荐答案

别无他法.您的尝试已经正确.这是唯一的办法.干杯!

No other way. Your attempt is already correct. That's the only way. Cheers!

useEffect() 只允许依赖,没有条件属性.

useEffect() only allows dependencies and no conditional attributes.

这篇关于我可以使用“UseEffect"吗?只有一定的价值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆