既是同步也是异步
在事件回调和生命周期函数里面是异步
在定时器,原生dom事件,promise中是同步
一个函数里面多次异步setState:
多次次函数模式setState会合并一次
2(执行顺序) ==> 0(输出值)
class StateTest extends React.Component {
state = {
count: 0,
}
componentDidMount() {
this.setState({count: this.state.count + 1})
this.setState({count: this.state.count + 1})
console.log(‘[1]‘,this.state.count) // 2 ==> 0
this.setState(state => ({count: state.count + 1}))
this.setState(state => ({count: state.count + 1}))
console.log(‘[2]‘,this.state.count) // 3 ==> 0
setTimeout(() => {
this.setState({count: this.state.count + 1})
console.log(‘timeout‘, this.state.count) // 10 ==> 6
this.setState({count: this.state.count + 1})
console.log(‘timeout‘, this.state.count) // 12 ==> 7
}, 0)
Promise.resolve().then(value => {
this.setState({count: this.state.count + 1})
console.log(‘promise‘, this.state.count) // 6 ==>4
this.setState({count: this.state.count + 1})
console.log(‘promise‘, this.state.count) // 8 ==> 5
})
}
render() {
const count = this.state.count
console.log(‘render‘, count) // 1 ==> 0 4 ==>3 5 ==>4 7 ==>5 9 ==>6 11 ==>7
return (
<div>
<p>{count}</p>
</div>
)
}
}
原文:https://www.cnblogs.com/teahouse/p/15242404.html