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 } }) } }