Is the interview always asked? ?

1. Event handlers controlled by React and life cycle functions calling setState will not be updated synchronously
New state.
2. Calling setState in events outside of React control is updated synchronously. For example, native js binding
Files, setTimeout/setInterval, etc.

class Example extends React.Component {
  constructor() {
    super()
    this.state = {
      val: 0
    }
  }
  componentDidMount() {
    this.setState({ val: this.state.val + 1 })
    console.log(this.state.val)
    // 第 1 次 log
    this.setState({ val: this.state.val + 1 })
    console.log(this.state.val)
    // 第 2 次 log
    setTimeout(() => {
      this.setState({ val: this.state.val + 1 })
      console.log(this.state.val)
      // 第 3 次 log
      this.setState({ val: this.state.val + 1 })
      console.log(this.state.val)
      // 第 4 次 log
    }, 0)
  }
  render() {
    return null
  }
} // 0, 0, 1, 2

万年打野易大师
1.5k 声望1.1k 粉丝