其他分享
首页 > 其他分享> > setState 数据合并

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

标签:prevState,return,counter,合并,state,props,数据,setState
来源: https://www.cnblogs.com/eric-share/p/15129326.html