-
Notifications
You must be signed in to change notification settings - Fork 47.5k
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
[FEATURE] implement a getState
method to get the sync state since setState
is async.
#12193
Comments
@xialvjun There's rfc which you may use to discuss |
@TrySound My proposal is not totally the same as that rfc. My proposal doesn't mutate any state. It's just get |
Can you show a real-world use case where you feel this is necessary? |
This is exactly what the callback is for. Are you not able to use it? class MyComponent extends Component {
state = { a: 1 }
method1 = () => {
this.setState({ a: 2 }, () => {
this.method2();
});
}
method2 = () => {
// Is log 2 in the console.
console.log(this.state.a);
}
// xxx...
} |
Well, it indeed can use the callback to ensure ... |
use case is just like this, What is the difference between passing an object or a function in setState? incrementCount() {
this.setState((prevState) => {
// Important: read `prevState` instead of `this.state` when updating.
return {count: prevState.count + 1}
});
}
handleSomething() {
// Let's say `this.state.count` starts at 0.
this.incrementCount();
this.incrementCount();
this.incrementCount();
// If you read `this.state.count` now, it would still be 0.
// But when React re-renders the component, it will be 3.
} Yeah, checkAndDoSomething() {
if (this.getState().count > 5) {
doSomething();
}
}
incrementCount() {
this.setState((prevState) => ({count: prevState.count + 1}))
}
incrementManyTimes(time) {
for (let i = 0; index < time; i++) {
this.incrementCount();
}
this.checkAndDoSomething();
} And in fact, we can change incrementCount() {
this.setState({count: this.getState().count + 1})
} Why should we use
|
Do you want to request a feature or report a bug?
FEATURE REQUEST
What is the current behavior?
What is the expected behavior?
The text was updated successfully, but these errors were encountered: