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             }         })      } }
上一篇:[Leetcode 152]最大乘积子串Maximum Product Subarray 踩坑


下一篇:[react] 为什么建议setState的第一个参数是callback而不是一个对象呢?