1. Render
- 一旦 Component 的
this.state
或者this.props
的值變化,那么當前 Component 將會被重新“繪制”。記住,是“繪制”而不是重新創建,因此this.getInitialState
、this.componentWillMount
和this.componentDidMount
不會因此而被調用。 - 通過變更
this.state
(this.setState
) 引起重繪是當前 Component 引起 “重繪” 的主要手段,還有一個手段是this.forceUpdate()
。而通過為 Child Component 設定新的props
的方式,是 Parent Component 引起 Child Component 重繪的主要方法。 - 判斷的時機是在一個重繪周期開始的時候,即一次
requestAnimationRequest
被回調的時候(1/60 秒)。所以,如果你的所有繪制時間在 16 秒之內被完成,用戶自然就能享受到如絲般柔順的交互了。React 可能是目前最容易 Tuning UI 性能的框架了,你只要分別記錄不同 Component 的 Render 執行時間就可以了。 - 檢測
this.state
或者this.props
的不同是通過“深度比較”來完成的,也就是說,只要整個對象樹的任何一個“葉子”的值變化,就將觸發“重繪”。所以你需要密切注意每一個 Component 的 state 和 props 到底綁定了多大范圍的數據,避免不必要的“重繪”。 - 你可以通過重載
this.shouldComponentUpdate
替代 React 的深度比較算法。但是,只有當你真的理得清楚的時候才使用這種方法。PureRenderMixin 完成了類似的工作。 - 更好地控制重繪,依賴于如何更好地將狀態的變化局部化。這就是 immutable-js 或者 mori 這樣的庫的作用了。每一個 Component 只綁定到大的數據容器的一個局部,其他部分的變化不會造成該 Component 綁定的
state
或者props
的變化,因此也就避免了不必要的“重繪”。 - 和JS 自己的
Array
和Object
相比, immutable-js 或者 mori 并非高性能的數據結構,但是其收獲的好處是狀態的隔離、快速判斷狀態是否變化(無需深度比較),以及由此帶來的最小化的“重繪”,在 React 的開發中是非常重要的。參見 性能比較。
2. Component Mount
- Component 在第一次被繪制前被 Mount,之前會執行
this.getInitialState
、this.componentWillMount
等一系列的類成員方法。React 的生命周期 文檔寫得很清楚。 - 但是,“重繪” 不會引發 Re-mount(你在 Parent Component 為 Child Component 設定新的 props,只會引起 Child Component 的 “重繪”,不會引起 Child Component 的 Re-mount(重新創建))。
- React 僅在兩種情況下會 Re-mount Component。一種是通過
React.render <div />
重新繪制了整個 Component Tree;還有一種就是 Parent Component 為 Child Component 設定了key
property,且當key
property 變化了的時候,老的 Child Component 被 Unmount 并銷毀,而新的 Child Component 被重新創建、初始化和 Mount。
在閱讀過基礎的 React 文檔之后,將上面的要點刻在腦子里,基本上 React 對你來說就沒什么坑了。如果上面的內容沒有理解就開始編程,那么即使是 React 也幫不上你什么了。