请看下面代码,在 componentDidMount 中使用 setState 时,请问是异步执行还是同步执行?如果是异步执行,为什么浏览器渲染界面时被阻塞了,当我用 SetTimeout 后就不会发生阻塞浏览器渲染界面,第一次的 render 能正常显示到界面上,求解!
import React, { useState, useEffect } from 'react';
function sleep(time) {
const now = Date.now();
while (Date.now() - now <= time * 1000) {}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
styles: {
height: '50px',
width: '50px',
backgroundColor: 'blue',
transition: 'all 1s',
textAlign: 'center',
color: 'white',
},
value: '1',
};
}
componentDidMount() {
//组件插入dom树后立即执行
console.log(document.querySelector('#box').innerHTML);
/*setTimeout(() => {
this.setState({
styles: { ...this.state.styles, height: '100px' },
value: '2',
});
}, 5000);*/
this.setState({
styles: { ...this.state.styles, height: '100px' },
value: '2',
});
}
render() {
console.log('App render');
return (
<>
<div id="box" style={this.state.styles}>
{this.state.value}
</div>
</>
);
}
}
export default App;
我看并没有阻塞呀,不使用setTimeout,也能看到更新后的值:2。

运行效果使用的代码。