Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
523 views
in Technique[技术] by (71.8m points)

javascript - React slow setState at console.log

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

'' on H

'H' on HE

'E' on HEL

'L' on HELL

'L' on HELLO

How is that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...