async () => this.setstate()

2019-08-25  本文已影响0人  小茶叶叶

这段代码的输出什么

handleChange = (e) => {
  this.setState({[e.target.name]: e.target.value})
  console.log('synchronous code')
}

changeAndValidate = async (e) => {
  await this.handleChange(e)
  console.log('asynchronous validation code')
}

componentDidUpdate() {
  console.log('updated component')    
}

https://codesandbox.io/s/hardcore-mclean-mb3zt
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
output:

synchronous code
updated component
asynchronous validation code

发生了什么

  1. changeAndValidate 函数之后的代码 只有await resolve this.handleChange函数的返回值之后, 才会执行下去
  2. this.handleChange 函数里面, 首先 setState 更新state的值,但setState 不一定是立即执行的,(react内部对setState 优化处理,不是每setState一次都会重新render一次,那样太吃性能了, 所以不必要为了把所有的setState写到一起 而让代码可读性变差),
    然后 执行 console.log('synchronous code')
    然后 返回一个 undefined
  3. await 就拿到了一个 undefined,undefined 不是一个promise,通过 Promise.resolve(undefined),变成一个 resolved promise,放在异步队列等待,
  4. 然后 event loop 执行到 componentDidUpdate ,console
  5. 然后 event loop里面空了,执行 Promise.resolve
  6. 然后, 执行await 后面的 console

相关资料:
https://stackoverflow.com/questions/47019199/why-does-async-await-work-with-react-setstate

https://medium.com/front-end-weekly/async-await-with-react-lifecycle-methods-802e7760d802

上一篇下一篇

猜你喜欢

热点阅读