React 生命周期函数 componentDidMount 渲染界面阻塞问题?

请看下面代码,在 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;
阅读 1.7k
1 个回答
✓ 已被采纳

我看并没有阻塞呀,不使用setTimeout,也能看到更新后的值:2。

运行效果使用的代码

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题