Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...