Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

精读《Javascript 事件循环与异步》 #41

Closed
ascoders opened this issue Oct 30, 2017 · 2 comments
Closed

精读《Javascript 事件循环与异步》 #41

ascoders opened this issue Oct 30, 2017 · 2 comments

Comments

@ascoders
Copy link
Owner

本周阅读的文章:传送门

事件循环作为 js 的基础特性,掌握后可以提高每一行代码的质量。

@ascoders ascoders mentioned this issue Oct 30, 2017
65 tasks
@ascoders ascoders closed this as completed Nov 4, 2017
@hardfist
Copy link

hardfist commented Nov 4, 2017

第一段代码等价于

componentWillMount() {
    return new Promise(resolve => {
      this.setState({
        a: 1
      })
      resolve();
    })
  }

React 不会对componentWillMount进行await调用,new Promise(resolver)里的resolver是同步执行的,所以实际上这段代码就等价于this.setState({a:1}),componentWillMount中同步调用setState不会触发rerender。
而第二段代码等价于

 componentWillMount() {
    return new Promise(resolve => {
      return Promise.resolve().then(() => {
        this.setState({
          a: 1
        })
      })
    })
  }

这里的setState是在内部Promise的then回调里执行的,所以是异步执行的,所以会触发rerender。
所以两者的区别只是在于在componentWillMount里是同步执行还是异步执行的而已。

@negativeentropy9
Copy link

第一段代码等价于

componentWillMount() {
    return new Promise(resolve => {
      this.setState({
        a: 1
      })
      resolve();
    })
  }

React 不会对componentWillMount进行await调用,new Promise(resolver)里的resolver是同步执行的,所以实际上这段代码就等价于this.setState({a:1}),componentWillMount中同步调用setState不会触发rerender。
而第二段代码等价于

 componentWillMount() {
    return new Promise(resolve => {
      return Promise.resolve().then(() => {
        this.setState({
          a: 1
        })
      })
    })
  }

这里的setState是在内部Promise的then回调里执行的,所以是异步执行的,所以会触发rerender。
所以两者的区别只是在于在componentWillMount里是同步执行还是异步执行的而已。

老铁 666

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants