React的Transaction浅析
1.兩個示例
- 示例1
輸出為
render 2
componentDidMount 2
- 示例2
點擊后this.state.clicked遞增1,而不是遞增2。
2.解釋
首先介紹React的Transaction。
其源碼在React/lib/Transaction.js。
Transaction就是給需要執(zhí)行的方法fn用wrapper封裝了 initialize 和 close 方法。且支持多次封裝。再通過 Transaction 提供的 perform 方法執(zhí)行。 perform執(zhí)行前,調(diào)用所有initialize 方法。perform 方法執(zhí)行后,調(diào)用所有close方法。
Transaction的use case是
Restoring selection even in the event of an unexpected error.
while guaranteeing that afterwards, the event system is reactivated.
reconciliation takes place in a worker thread.
content.
to preserve the scrollTop (an automatic scroll aware DOM).
示例一,對應(yīng)的是第4點use case。整個生命周期就是一個Transaction,在Transaction執(zhí)行期間,componentDidUpdate方法被推入一個隊列中。DOM reconciliation后,再調(diào)用隊列中的所有componentDidUpdate。
示例二,對應(yīng)的是第3點use case。react的事件回調(diào)也是一個Transaction。handleClick里面的this.setState不會馬上生效,而是先通過 ReactUpdates.batchedUpdate 方法存入臨時隊列。所以每次setState時,拿到的this.state.clicked都是初始值。直到transaction 完成,通過ReactUpdates.flushBatchedUpdates方法進行UI更新。
更詳細的流程參考此圖
3.參考文章(強烈推薦去看)
http://undefinedblog.com/what-happened-after-set-state/
http://zhuanlan.zhihu.com/purerender/20328570
總結(jié)
以上是生活随笔為你收集整理的React的Transaction浅析的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ZeroC Ice启用SSL通讯的配置
- 下一篇: $(document).ready();