深入理解 react setState 机制

2020-04-07  本文已影响0人  阿畅_

react setState 机制

记住这几个字 不可变值

数据更新可能是异步的

  this.setState({
    count: this.state.count + 1
  }, () => {
    // 在回调函数中,可以拿到最新的值
    // 这里相当于使用 Vue 的 $nextTick
    console.log(this.state.count)
  })

  // 这里使用时 异步的,直接获取拿不到最新的值
  console.log(this.state.count) 
  setTimeout(() => {
    this.setState({
      count: this.state.count
    })
  })
  document.body.addEventListener('click', () => {
    this.setState({
      count: this.state.count
    })
  })
  state = {
  count: 0
}

handleClick = () => {
  this.setState({
    count: this.state.count + 1
  })
  this.setState({
    count: this.state.count + 1
  })
  this.setState({
    count: this.state.count + 1
  })
  // 传入对象,会被合并,执行一次结果
  console.log('count---->', this.state.count) // 0 再次执行会是 1,2,3
}

render() {
  return (
    <div onClick={this.handleClick}>测试</div>
  )
}
image.png
state = {
    count: 0
  }

  handleClick = () => {
    this.setState((prevState, props) => {
      return {
        count: prevState.count + 1
      }
    })
    this.setState((prevState, props) => {
      return {
        count: prevState.count + 1
      }
    })
    this.setState((prevState, props) => {
      return {
        count: prevState.count + 1
      }
    })
    console.log('count ------->', this.state.count) // 0,3,6
  }

  render() {
    return (
      <div onClick={this.handleClick}>测试</div>
    )
  }
image.png
setState 主流程
主流程.png

batchUpdate 机制

简单理解为: 当函数执行开始时 isBatchingUpdates 是 true 然后执行正常代码逻辑,函数执行结束时,isBatchingUpdates 是 false

  handleClick() {
    // 开始处于 isBatchingUpdates , isBatchingUpdates = true
    this.setState({
      count: this.state.count + 1
    })
    // 结束 isBatchingUpdates = false
  }

但如果 setState 是异步时

  handleClick() {
    // 开始处于 isBatchingUpdates , isBatchingUpdates = true
    setTimeout(() => {
      // 此时运行 setState , isBatchingUpdates 的值已经是 false
      this.setState({
        count: this.state.count + 1
      })
    })

    // 结束 isBatchingUpdates = false
  }

transaction 事务机制

  handleClick() {
    // 开始处于 isBatchingUpdates , isBatchingUpdates = true
    // initialize

    // 自定义的方法 或者业务代码
    this.setState({
      count: this.state.count + 1
    })

    // close
    // 结束 isBatchingUpdates = false
  }
transaction.png

每天进步一点点 💪

上一篇 下一篇

猜你喜欢

热点阅读