在反应中使用 useState 钩子时,在设置后立即读取组件状态 [英] Reading component state just after setting when using useState hook in react

查看:38
本文介绍了在反应中使用 useState 钩子时,在设置后立即读取组件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个 console.log 不起作用:它只会打印先前的状态值,因为 setasync.

This console.log is not working: It'll just print the previous state value as set is async.

const SomeCompo = () => {
  const [count, set] = useState(0);
  const setFun = () => {
    console.log(count);
    set(count + 1);
    console.log(count);    
  }
  return <button onClick={setFun}>count: {count}</button>
}

我必须读取渲染本身的计数:

I had to read the count in the render itself:

const SomeCompo = () => {
  const [count, set] = useState(0);
  console.log(count);
  const setFun = () => {
    set(count + 1);
  }
  return <button onClick={setFun}>count: {count}</button>
}

有没有更好的方法来读取值,因为我不想在每次渲染时都进行控制台.

Is there a better way to read the value as I don't want to console for every render.

推荐答案

您可以使用 useEffect 为此,

You can use useEffect for this,

useEffect(() => {
   console.log(count);
}, [count]) //[count] is a dependency array, useEffect will run only when count changes.

这篇关于在反应中使用 useState 钩子时,在设置后立即读取组件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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