本文介绍: 在react18版本之前setState可以同步可以异步的。在Promise状态更新js原生事件定时器中是同步的。在react18版本之后是setState异步的。在react的合成事件中,是异步的。如何拿到setstate更新的值。

react18版本之前setState可以同步可以异步

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

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

react18版本之后是setState异步的

 代码

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&gt;
                <h2&gt;{this.state.count}</h2&gt;
                <button onClick={this.add}>增加</button>
            </div>
        );
    }
}

export default Async;

如何拿到setstate更新的值

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

函数写法

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

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注