setState 数据合并

import React, { Component } from 'react'

export default class App extends Component {

    constructor(props){
        super(props)
        this.state = {
            counter:0,
            name:'Eric'
        }
    }
    render() {
        return (
            <div>
                <h2>当前计数: {this.state.counter}</h2>
                <h2>{this.state.name}</h2>
                <button onClick={e=>this.increment()}>+1</button> 
            </div>
        )
    }
 
    increment(){   
        
        // 1 setState 本身被合并
        // this.setState({
        //     counter: this.state.counter + 1
        // })   

        // this.setState({
        //     counter: this.state.counter + 1
        // })

        // 2 setState 合并时进行累加
        this.setState((prevState,props)=>{
            return {
                counter: prevState.counter + 1
            }
        }) 

        this.setState((prevState,props)=>{
            return {
                counter: prevState.counter + 1
            }
        }) 

        this.setState((prevState,props)=>{
            return {
                counter: prevState.counter + 1
            }
        }) 
    }
}
posted @ 2021-08-11 17:29  13522679763-任国强  阅读(227)  评论(0)    收藏  举报