为什么 React setState 钩子没有立即更新? [英] Why is React setState hook not updating immediately?

查看:60
本文介绍了为什么 React setState 钩子没有立即更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从父函数调用处理程序,并将更新的状态值作为参数,但是,在调用 setSelected 后状态不会立即更新,因为两个控制台日志都打印 false(初始值).但是,在 onClick 函数完成后,它会更新.

I am trying to call a handler from a parent function with the updated state value as an argument, however, the state does not update immediately after the setSelected is called as both console logs are printing false(the initial value). After the onClick function is completed however, it gets updated.

onClick={() => {
        console.log("Clicked: ", props.rank, props.suit, selected); 
        setSelected(!selected)
        console.log("selected: ", selected)
        // props.handle_card_selected(props.id, selected)
      }}

useEffect(() => {
    const check_border = () => {
      if (selected) {
        return "green"
      }
      return "black"
    }
    check_border()
  }, [selected])

推荐答案

关于 React 中的状态更新你需要知道的两件事:

Two things you need to know about the state update in React:

  • 状态是异步更新的
  • 在任何特定的渲染中,状态和道具都不会改变,只有在组件重新渲染时才会反映变化

如果要记录selected的更新值,请将日志语句放在useEffect钩子中.

If you want to log the updated value of selected, put the log statement in the useEffect hook.

你不能在同一个渲染中更新和记录任何状态变量的更新值;由于状态更新,组件将不得不重新渲染以反映更改.

You can't update and log the updated value of any state variable in the same render; component will have to re-render to reflect changes due to state update.

同样,如果你想用selected的更新值调用一个函数,从useEffect钩子内部调用该函数.

Similarly, if you want to call a function with the updated value of selected, call the function from inside the useEffect hook.

这篇关于为什么 React setState 钩子没有立即更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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