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

Categories

0 votes
478 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 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...