setState 获取异步更新数据的两种方法

时间:2021-08-11
本文章向大家介绍setState 获取异步更新数据的两种方法 ,主要包括setState 获取异步更新数据的两种方法 使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
import React, { Component } from 'react'

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {
            counter:0
        }
    }
    render() {
        return (
            <div>
                <h2>当前计数: {this.state.counter}</h2>
                <button onClick={e=>this.increment()}>+1</button>
            </div>
        )
    }

     // 获取异步更新的数据
     // 方式二 
    componentDidUpdate(){
        console.log('componentDidUpdate:',this.state.counter);
    }

    increment(){ 
        //  setState 异步更新
        // this.setState({
        //     counter: this.state.counter + 1
        // })
        // console.log(this.state.counter); 

        // 获取异步更新的数据
        // 方式一 , 回调函数
        this.setState({
            counter: this.state.counter + 1
        },()=>{
            console.log('回调函数:',this.state.counter);
        })
    }
}
我是Eric,手机号是13522679763

原文地址:https://www.cnblogs.com/eric-share/p/15128918.html