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

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

问题描述

让我们说我有一个状态,该状态取决于其他状态(例如,当A更改时,我希望B更改).

创建一个观察A并将其设置在useEffect钩内的B的钩子合适吗?

效果会级联,以便当我单击按钮时,第一个效果将触发,导致b改变,导致第二个效果在下一次渲染之前触发?这样的代码结构在性能方面有不利之处吗?

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>
  )
}

解决方案

效果始终在渲染阶段完成后执行,即使您将setState置于一个效果内,另一个效果也将读取更新后的状态并仅在该状态后对其执行操作渲染阶段.

已经说过,除非有可能由于changing a之外的其他原因导致b可能发生变化,否则最好以相同的效果执行两个动作,在这种情况下,您也希望执行相同的逻辑

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

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

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.

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天全站免登陆