前端小誌(轉型中)

一個用來記錄人老會忘記的地方

React的setState非同步行為

2017年07月28日
其實我想很多人都知道React的setState是非同步的行為,但是通常還是會順順地使用它,直到他真的發生了奇妙的事情以後,才會開始認真思考這個問題。

沒錯,那個認真思考問題的人就是我。在專案裡面的登入頁面中,被埋了sleep 1秒的code,前人告訴我那是為了他debug方便而寫的,當我把這行code拿掉的時候,怎麼登都無法登入,這時候我臉上都冒出三條線了...

一定很多人都看過React的官方文件

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

在react的github上也很多人再討論是否要加入promise的功能,因為開發者說明performance issues就不提供了。

不過其實setState提供了callback方法。(很顯然大家不喜歡寫callback)

this.setState(state, callback);

整理以後可以寫成下方的這種形式,就可以接者await使用

class extends Component {
    setStateAsync = state => new Promise((resolve)=>{
      this.setState(state, resolve);
    });

}

這樣我要來解我的登入BUG了..


展開Disqus
分類
最近文章
友站連結
© 2019 Ernie Yang