[英]state is immediately available when setState is called after await
When calling setState after awaiting for another function and logging the state to the console - the value is immediately available. 在等待另一个函数并将状态记录到控制台后调用setState时 - 该值立即可用。
I know that setState is asynchronous and in all other cases, it wouldn't be available immediately after calling it (but would be available in the setState callback) 我知道setState是异步的,在所有其他情况下,它在调用后不会立即可用(但在setState回调中可用)
When used without await (expected) 在没有等待的情况下使用(预期)
// inital value state is 0
const response = fetchSomething()
this.setState({
value: 5
})
console.log(this.state.value) // prints 0
Used with await 与等待一起使用
// inital value state is 0
const response = await fetchSomething()
this.setState({
value: 5
})
console.log(this.state.value) // prints 5
What am I missing here? 我在这里错过了什么?
When you make a function async
and you await
some expression, the following statements will be run after the awaited promise has been resolved under the hood. 当你创建一个async
函数并await
一些表达式时,下面的语句将在等待的promise被解决之后运行。
The documentation states that setState() does not always immediately update the component , and it usually doesn't, but in this case when you update the state after a promise has been resolved in an event handler the state is updated immediately. 文档声明setState()并不总是立即更新组件 ,它通常不会,但在这种情况下,当您在事件处理程序中解析了promise之后更新状态时,状态会立即更新。
Example 例
class App extends React.Component { state = { value: 0 }; asyncClick = () => { Promise.resolve().then(() => { this.setState({ value: 5 }); console.log(this.state.value); }); }; syncClick = () => { this.setState({ value: 5 }); console.log(this.state.value); }; render() { return ( <div> <div>{this.state.value}</div> <button onClick={this.asyncClick}>Async click</button> <button onClick={this.syncClick}>Sync click</button> </div> ); } } ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.