-
Notifications
You must be signed in to change notification settings - Fork 47.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Bug: Field value does not change #19326
Comments
The solution to this problem is to define a function in onClick, not a function call. Instead of onclick={onClickHandler}, Use onclick={()=>onClickHandler()} or if you don't use arrow funciton onclick={function(){onClickHandler()}} |
I think it's because setState has asynchronous characteristics. The first call will be ignored. If you have the same key to run setState, the last key delivered takes precedence. |
import React, { Component } from 'react';
class App extends Component {
state = {
count: 0
}
add() {
this.setState({count: this.state.count+1});
}
handleClick() {
this.add();
this.add();
this.add();
}
render() {
return (
<div>
<p>{this.state.count}</p>
<button onClick={() => this.handleClick()}>Add</button>
</div>
);
}
}
export default App; The intention of this code is to increase the value of this.state.count by three. This is because setState calls are made asynchronously. SetState queues changes without immediate updating of components and updates them in batches with multiple changes. This means that if you call the setState several times, only one rendering can be done, so this.state will have only one value without changing during multiple setState operations. |
but in my situation I need to change the "offset" field to 0, how to do it right? |
|
React version: 16.13.1
Link to code example: https://repl.it/@Sc_Ximik/Create-React-App
The current behavior
If I call the "update" method, through the "onClickHandler" method, my offset field does not change to 0
The expected behavior
If I call the "update" method, through the "onClickHandler" method, my offset field changes to 0
The text was updated successfully, but these errors were encountered: