在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>
- <h2>{this.state.count}h2>
- <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)}
- );