笔记二十五、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)}
);
相关推荐
paopaokaka_luck3 小时前
宠物门店经营管理系统(销售与库存联动、进货自动记账、 退换与退款关联、员工个人业绩、ECharts 经营分析、滞销识别与客户分层、宠物档案年龄计算)
前端·javascript·spring boot·mysql·echarts·mybatis·1024程序员节
空中湖4 小时前
用 React 写数据大屏:为什么我不建议用图表库
前端·react.js·前端框架
解决小子7 小时前
【虚幻引擎】【C++】【GAS框架】构建角色基类、属性集、数值钳制
c++·笔记·游戏引擎·虚幻·gas·能力系统
鶴哥只手遮天7 小时前
jQuery 4.0 源码架构与工程实践-第 10 章 尺寸、几何与显隐
前端·javascript·jquery
破芽8 小时前
learn-claude-code-s05-s11-学习笔记
笔记·学习
米米商聊9 小时前
图标能点,按钮就可用了吗?键盘、名称与收藏状态
前端·javascript
程序猿乐锅9 小时前
【从0-1学习Python | 第七篇】Python 面向对象基础
开发语言·笔记·后端·python·学习·1024程序员节
fish_zzzz10 小时前
笔记--浅谈内存,存储空间,BIOS芯片,显卡GPU、VRAM(1)
笔记·1024程序员节
ACP广源盛1392462567310 小时前
PCIe Gen3 交换芯片选型笔记:多路扩展方案 IX7024@ACP 评估
笔记·硬件架构·pcie·国产芯片
深圳老胡10 小时前
STM32 开发中 Trae 内置模型怎么选:Seed、MiniMax、GLM、DeepSeek、Kimi、Qwen 全对比
笔记·stm32·单片机·嵌入式硬件·代码规范·1024程序员节