react setState同步、异步问题

setState

1. 在 React 的事件中,表现为异步

changeCount = () => {
    this.setState({
      count: this.state.count + 1
    })
    console.log(this.state.count)
  }

<button onClick={this.changeCount}>add</button>

2. 在原生事件中,表现为同步

componentDidMount() {
    this.btn.current.addEventListener('click', ()=>{
      this.setState({
        count: this.state.count + 1
      })
      console.log('原生', this.state.count)
    }, false);
  }

<button ref={this.btn}>原生add</button>

如何在React的事件中表现同步呢?
可以给setState添加回调函数:

this.setState({
    count: 100
}, ()=>{
    console.log('回调', this.state.count)
})

React中,setState有两种写法:
1. 用对象的方式

this.setState({
    count: 100
})

2. 用函数的方式

this.setState((state, props) => {
    return {
        count: 100
    }
}

完整代码

import React, { Component } from 'react';

class SetStateDemo extends Component {

  constructor() {
    super();
    this.state = {
      count: 1
    }
    this.btn = React.createRef();
  }

  changeCount = () => {
    this.setState({
      count: this.state.count + 1
    })
    console.log(this.state.count)
  }

  changeCount_call = () => {
    this.setState({
      count: this.state.count + 1
    }, ()=>{
      console.log('回调', this.state.count)
    })
  }

  changeCount_fn = () => {
    this.setState((state, props) => {
      return {
        count: state.count + 1
      }
    }, ()=>{
      console.log('fn 回调', this.state.count)
    })
    console.log('fn', this.state.count)
  }

  componentDidMount() {
    this.btn.current.addEventListener('click', ()=>{
      this.setState({
        count: this.state.count + 1
      })
      console.log('原生', this.state.count)
    }, false);
  }

  render() {
    return (
      <div>
        <div>{this.state.count}</div>
        <button onClick={this.changeCount}>add</button>
        <button onClick={this.changeCount_call}>回调add</button>
        <button onClick={this.changeCount_fn}>fn add</button>
        <button ref={this.btn}>原生add</button>
      </div>
    );
  }
}

export default SetStateDemo;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值