React.PureComponent
它用當前與以前 props 和 state 的淺比較覆寫了 shouldComponentUpdate()
的實現。
簡單來講,就是PureComponent簡單實現了shouldComponentUpdate()的功能
固然,若是你的數據結構比較複雜就不行了react
首先看看第一段代碼數據結構
1 import React from 'react' 2 3 class Child extends React.Component { 4 5 render() { 6 console.log('child render') 7 return <div>child</div>; 8 } 9 } 10 11 class App extends React.Component { 12 state = { 13 a: 1, 14 }; 15 16 render() { 17 console.log('render'); 18 return ( 19 <> 20 <button 21 onClick={() => { 22 this.setState({ a: 2 }); 23 }} 24 > 25 Click me 26 </button> 27 <Child color={'red'}/> 28 </> 29 ); 30 } 31 } 32 33 export default App
當咱們點擊按鈕更新了父組件的狀態,那麼子組件也會從新render,那麼這個時候輸出的是:優化
parent render
child renderthis
當咱們想優化組件render的時候,咱們會使用shouldComponentUpdate() 。那麼我如今把上面的 Child 組件替換爲以下:spa
1 class Child extends React.Component { 2 3 shouldComponentUpdate(nextProps, nextState) { 4 if (this.props.color !== nextProps.color) { 5 return true 6 } 7 } 8 9 render() { 10 console.log('child render') 11 return <div>child</div>; 12 } 13 }
這個時候,咱們點擊按鈕更新父組件狀態的時候,子組件的是不會render的,輸入的是:code
parent renderblog
最後,咱們在把child組件替換爲以下:console
1 class Child extends React.PureComponent { 2 render() { 3 console.log('child render') 4 return <div>child</div>; 5 } 6 }
你會發現它和上圖的Child組件是同樣的效果,一樣只輸出了:class
parent renderimport