如何在反应钩子上使用`setState`回调 [英] How to use `setState` callback on react hooks

查看:35
本文介绍了如何在反应钩子上使用`setState`回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

React hooks 引入了 useState 来设置组件状态.但是我如何使用钩子来替换如下代码的回调:

React hooks introduces useState for setting component state. But how can I use hooks to replace the callback like below code:

setState(
  { name: "Michael" },
  () => console.log(this.state)
);

我想在状态更新后做点什么.

I want to do something after the state is updated.

我知道我可以使用 useEffect 来做额外的事情,但我必须检查状态以前的值,这需要一些代码.我正在寻找一个可以与 useState 钩子一起使用的简单解决方案.

I know I can use useEffect to do the extra things but I have to check the state previous value which requires a bit code. I am looking for a simple solution which can be used with useState hook.

推荐答案

你需要使用 useEffect 钩子来实现.

You need to use useEffect hook to achieve this.

const [counter, setCounter] = useState(0);

const doSomething = () => {
  setCounter(123);
}

useEffect(() => {
   console.log('Do something after counter has changed', counter);
}, [counter]);

这篇关于如何在反应钩子上使用`setState`回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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