React面试题---setState是同步执行还是异步执行?

1. React中 setState是同步执行还是异步执行?什么时候是同步什么时候是异步?

 1 import React, { Component } from "react";
 2 import ReactDOM from "react-dom";
 3 // this.setState 到底是同步的还是异步的?
 4 class App extends Component {
 5     state = {
 6        num: 0
 7     };    
 8     onClick = () => {
 9       console.log("更新前,num:",this.state.num);
10       this.setState({
11           num: this.state.num + 1
12       });
13       console.log("更新后,num:",this.state.num);
14     };
// 打印得到的结果是: 0,0;
15 render() { 16 const { num } = this.state; 17 return ( 18 <div> 19 <h1>{num}</h1> 20 <button onClick={this.onClick}>+1</button> 21 </div> 22 ) 23 } 24 }
// 上述验证得到结果是异步执行


import React, { Component } from "react"; import ReactDOM from "react-dom"; // this.setState 到底是同步的还是异步的? class App extends Component { state = { num: 0 }; onClick = () => { console.log("更新前,num:",this.state.num); setTimeOut(()=>{ this.setState({ num: this.state.num + 1 }); console.log("更新后,num:",this.state.num); },1000) }; // 打印得到的结果是: 0,1; render() { const { num } = this.state; return ( <div> <h1>{num}</h1> <button onClick={this.onClick}>+1</button> </div> ) } } // 上述验证得到结果是同步执行

  总结:在react中,setState是异步执行,若将setState放在异步代码中,则为同步执行。

posted @ 2023-02-09 17:08  zhijie_wang  阅读(48)  评论(0)    收藏  举报