React 钩子状态未在日志中更新 [英] React hooks states aren't updating in log

查看:37
本文介绍了React 钩子状态未在日志中更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我写

function Component() {
  const [isLoading, setLoading] = useState(true);
  const request = () => {
    setLoading(true)
    console.log(isLoading)
    setLoading(false)
    console.log(isLoading)
  }
}

它两次都会注销true".为什么控制台中的状态没有更新?尽管它在 DOM 中运行良好.

It will log out 'true' both times. Why isn't the state updating in the console? Eventhough it works fine in the DOM.

this.setState({ ...} 将显示新的状态值

推荐答案

使用 setStateuseState 钩子在 state 中设置新值是一个异步过程.

Setting a new value in state by using setState or useState hook is an asynchronous process.

如果你想在它改变后记录新值,你必须将它与useEffect钩子结合

If you want to log the new value once it has changed, you have to couple it with the useEffect hook

useEffect(() => {
  console.log(isLoading)
}, [isLoading]);

这篇关于React 钩子状态未在日志中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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