React中setState合并
作者:互联网
this.setState中的操作默认会合并
import React, { Component } from 'react'
export default class App extends Component {
constructor() {
super()
this.state = {
counter: 0
}
}
render () {
return (
<div>
<h2>{this.state.counter}</h2>
<button onClick={() => this.increase()}>+1</button>
</div>
)
}
increase() {
// this.setState({
// counter: this.state.counter + 1
// })
// this.setState({
// counter: this.state.counter + 1
// })
// 点击一次按钮,虽然进行了两次加一操作,但是两次会合并,counter结果是 1
// 给setState里面传一个函数就能解决这个问题, 上一次的值会传给prevState保存,想知道原理可以去看源码
this.setState((prevState, props) => {
return {
counter: prevState.counter + 1
}
})
this.setState((prevState, props) => {
return {
counter: prevState.counter + 1
}
})
// 结果为2
}
}
标签:increase,prevState,return,counter,合并,React,state,setState 来源: https://blog.csdn.net/sexnmaa/article/details/116399949