问题
my function looks like this:
this.setState(prevState => ({
time : prevState.time + 1
}), function() {
doSomethingWithNewState(this.state.time)
})
is it correct to use await in this situation? like this:
await this.setState(prevState => ({
time : prevState.time + 1
}));
doSomethingWithNewState(this.state.time);
回答1:
No this.setState
doesn't return a promise.
So you can't use await in this case. You need to use the callback.
回答2:
As the previous answer mentioned, setState()
does not return a Promise, so you cannot use it with await
as you intend. (Although you can await
synchronous code as well).
When it's said that setState()
is asynchronous, what's meant is that the effect of setState()
may happen at a later time.
Furthermore, while reading this.state
in the callback function will give you the state of the component at that particular moment in time when the callback gets executed, it's not exactly what you'd expect, because all callback functions are called after a batch of setState()
calls gets executed. (See this issue).
回答3:
setState
takes a callback? Not sure why the first example would be an issue
https://medium.learnreact.com/setstate-takes-a-callback-1f71ad5d2296
回答4:
You can't await this.setState
for the reasons already stated. But you can write your own awaitable setState funtion easily:
promisedSetState = (newState) => new Promise(resolve => this.setState(newState, resolve));
now you can call
await pwomisedSetState({ someState: true });
来源:https://stackoverflow.com/questions/51968714/is-it-correct-to-use-await-setstate