React避免重復渲染
React在渲染出的UI內(nèi)部建立和維護了一個內(nèi)層的實現(xiàn)方式,它包括了從組件返回的React元素。這種實現(xiàn)方式使得React避免了一些不必要的創(chuàng)建和關聯(lián)DOM節(jié)點,因為這樣做可能比直接操作JavaScript對象更慢一些,它被稱之為“虛擬DOM”。
當一個組件的props或者state改變時,React通過比較新返回的元素和之前渲染的元素來決定是否有必要更新實際的DOM。當他們不相等時,React會更新DOM。
在一些情況下,你的組件可以通過重寫這個生命周期函數(shù)shouldComponentUpdate來提升速度, 它是在重新渲染過程開始前觸發(fā)的。 這個函數(shù)默認返回true,可使React執(zhí)行更新:
shouldComponentUpdate(nextProps, nextState) { return true;}舉例
如果想讓組件只在props.color或者state.count的值變化時重新渲染,你可以像下面這樣設定shouldComponentUpdate:
class CounterButton extends React.Component { constructor(props) { super(props); this.state = {count: 1}; } shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; } return false; } render() { return ( <button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button> ); }}在以上代碼中,shouldComponentUpdate只檢查props.color和state.count的變化。如果這些值沒有變化,組件就不會更新。當你的組件變得更加復雜時,你可以使用類似的模式來做一個“淺比較”,用來比較屬性和值以判定是否需要更新組件。這種模式十分常見,因此React提供了一個輔助對象來實現(xiàn)這個邏輯 - 繼承自React.PureComponent。以下代碼可以更簡單的實現(xiàn)相同的操作:
class CounterButton extends React.PureComponent { constructor(props) { super(props); this.state = {count: 1}; } render() { return ( <button color={this.props.color} onClick={() => this.setState(state => ({count: state.count + 1}))}> Count: {this.state.count} </button> ); }}PureComponent
原理
當組件更新時,如果組件的 props 和 state 都沒發(fā)生改變, render 方法就不會觸發(fā),省去 Virtual DOM 的生成和比對過程,達到提升性能的目的。具體就是 React 自動幫我們做了一層淺比較:
if (this._compositeType === CompositeTypes.PureClass) { shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);}而 shallowEqual 又做了什么呢?會比較 Object.keys(state | props) 的長度是否一致,每一個 key 是否兩者都有,并且是否是一個引用,也就是只比較了第一層的值,確實很淺,所以深層的嵌套數(shù)據(jù)是對比不出來的。
新聞熱點
疑難解答
圖片精選