在console.log上反应慢的setState [英] React slow setState at console.log

查看:78
本文介绍了在console.log上反应慢的setState的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的React组件,它的输入字段带有一个onChange事件.触发onChange事件,并使用输入字段中的值更新某些组件状态.但是,我在控制台记录日志时注意到状态是背后的一个字符.因此,如果我输入"Hello",控制台将显示状态为

I have a simple React component which has a input field with an onChange event attached. The onChange event fires, and updates the some component state with the value from the input field. However i noticed when console logging that the state is one character behinde. So if i type "Hello" the console shows the state to be

''在H

HE上的"H"

HEL上的"E"

'H'在地狱

HELLO上的"L"

'L' on HELLO

那怎么样?

推荐答案

this.setState 是异步的.这意味着记录的时间控制台无法与更新的时间状态匹配如果要在状态更改后看到确切的值,则必须执行以下操作

this.setState is asynchronous. It means that the time console logged could not be matched with the time state got updated If you want to see exact value after state got changed, you have to do as below

this.setState({ 'updated': 'state'}, () => {
  console.log(this.state.updated);
});

这篇关于在console.log上反应慢的setState的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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