【发布时间】:2019-02-27 17:20:25
【问题描述】:
我在Codepen写了一个测试用例
单击按钮运行测试,然后从浏览器控制台查看结果。
从控制台日志可以看到,即使我多次调用setState之前 await,它也只会更新组件一次。
但是如果我多次调用setState之后 await,它也会多次更新组件。
知道为什么会这样吗?
代码:
/*
* A simple React component
*/
class Application extends React.Component {
state = {
value: 0
}
onClickHandler = (e) => {
this.runAsyncFunc();
}
runAsyncFunc = async() => {
console.log('BEFORE AWAIT');
this.setState({ value: 1 });
this.setState({ value: 1 });
this.setState({ value: 1 });
await setTimeout(()=>{}, 2000);
console.log('AFTER AWAIT');
this.setState({ value: 1 });
this.setState({ value: 1 });
this.setState({ value: 1 });
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log('updated');
}
render() {
return <div>
<p>{this.state.value}</p>
<button onClick={this.onClickHandler}>RUN TEST</button>
<p>Please check from Browser Console's Log</p>
</div>;
}
}
/*
* Render the above component into the div#app
*/
React.render(<Application />, document.getElementById('app'));
【问题讨论】:
-
setTimeout 不返回可以等待的承诺。
-
stackoverflow.com/a/48731782/2630817 这可能会有所帮助
-
另外,setState 本身是异步的,如果可以的话,React 会展平前三个调用。
-
@remix23 我知道 setState 是一个异步调用,但是为什么在 await 之后每次调用 setState 都会触发它?
标签: javascript reactjs