首页 > 其他 > 详细

react setState

时间:2021-09-10 04:24:47      阅读:38      评论:0      收藏:0      [点我收藏+]

既是同步也是异步
在事件回调和生命周期函数里面是异步

在定时器,原生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>
  )
}

}

react setState

原文:https://www.cnblogs.com/teahouse/p/15242404.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!