我可以在 useEffect 钩子内设置状态吗 [英] Can I set state inside a useEffect hook

查看:28
本文介绍了我可以在 useEffect 钩子内设置状态吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一些依赖于其他状态的状态(例如,当 A 更改时,我希望 B 更改).

Lets say I have some state that is dependent on some other state (eg when A changes I want B to change).

在 useEffect 钩子中创建一个观察 A 并设置 B 的钩子是否合适?

Is it appropriate to create a hook that observes A and sets B inside the useEffect hook?

效果是否会级联,当我单击按钮时,第一个效果将触发,导致 b 更改,导致第二个效果在下一次渲染之前触发?像这样构建代码是否有任何性能方面的缺点?

Will the effects cascade such that, when I click the button, the first effect will fire, causing b to change, causing the second effect to fire, before the next render? Are there any performance downsides to structuring code like this?

let MyComponent = props => {
  let [a, setA] = useState(1)
  let [b, setB] = useState(2)
  useEffect(
    () => {
      if (/*some stuff is true*/) {
        setB(3)
      }
    },
    [a],
  )
  useEffect(
    () => {
      // do some stuff
    },
    [b],
  )

  return (
    <button
      onClick={() => {
        setA(5)
      }}
    >
      click me
    </button>
  )
}

推荐答案

效果总是在渲染阶段完成后执行,即使你在一个效果中设置了状态,另一个效果也会读取更新的状态并在之后才对其采取行动渲染阶段.

Effects are always executed after the render phase is completed even if you setState inside the one effect, another effect will read the updated state and take action on it only after the render phase.

话虽如此,最好以相同的效果采取两种行动,除非 b 有可能因 change a 以外的原因而改变,在这种情况下你也想执行相同的逻辑

Having said that its probably better to take both actions in the same effect unless there is a possibility that b can change due to reasons other than changing a in which case too you would want to execute the same logic

这篇关于我可以在 useEffect 钩子内设置状态吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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