笔记二十五、React中setState是同步还是异步的?

在react18版本之前setState既可以是同步也可以是异步的

在Promise的状态更新、js原生事件、定时器中是同步的

在react的合成事件中,是异步的

在react18版本之后是setState异步的

代码

javascript 复制代码
import React, {Component} from 'react';

class Async extends Component {

    state = {count: 0}

    add = () => {
        // {count: this.state.count + 1}
        this.setState(() => ({count: this.state.count + 1}), () => {
            // 回调函数 获取更新的 state 值
            console.log('更新之后的值:', this.state.count)
        });
        console.log("更新前打印的值:", this.state.count)
    }

    render() {
        return (
            <div>
                <h2>{this.state.count}</h2>
                <button onClick={this.add}>增加</button>
            </div>
        );
    }
}

export default Async;

如何拿到setstate更新的值

javascript 复制代码
this.setState({ counte: this.state.counte + 1 }, () => {
  console.log("更新后的值:", this.state.counte);
});

函数写法

javascript 复制代码
this.setState(
  () => ({ counte: this.state.counte + 1 }),
  () => {console.log("更新后的值:", this.state.counte)}
);
相关推荐
GISer_Jing8 小时前
Three.js着色器编译机制深度解析
javascript·webgl·着色器
丷丩8 小时前
MapLibre GL JS第22课:查看本地GeoJSON
前端·javascript·map·mapbox·maplibre gl js
油炸自行车8 小时前
Claude Code 错误:API Error: 400 Failed to deserialize the JSON body into the
开发语言·javascript·json·trae·claude code·api error 400
sheeta19988 小时前
LeetCode 每日一题笔记 日期:2026.05.29 题目:3300. 最小元素
笔记·leetcode
中屹指纹浏览器9 小时前
2026指纹浏览器代理链路适配原理与多线路集群调度方案
经验分享·笔记
不羁的木木9 小时前
ArkWeb实战学习笔记05-综合实战:构建混合应用
笔记·学习·harmonyos
CC大煊9 小时前
一个Javaer的AI转型笔记(1):入坑LangChain,我的第一个hello world
笔记·langchain
元气少女小圆丶11 小时前
SenseGlove Nova 2+Unity开发笔记1
笔记·学习·unity
冰暮流星12 小时前
javascript之history对象介绍
前端·笔记
丷丩12 小时前
MapLibre GL JS第19课:实时更新要素
前端·javascript·gis·map·mapbox·maplibre gl js