Component 和 PureComponent 的區別;復制demo,肉眼可以的區別


React.PureComponent它用當前與之前 props 和 state 的淺比較覆寫了 shouldComponentUpdate() 的實現。
簡單來說,就是PureComponent簡單實現了shouldComponentUpdate()的功能
當然,如果你的數據結構比較復雜就不行了

首先看看第一段代碼

 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 render

當我們想優化組件render的時候,我們會使用shouldComponentUpdate() 。那么我現在把上面的 Child 組件替換為如下:

 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的,輸入的是:

parent render

 

最后,我們在把child組件替換為如下:

1 class Child extends React.PureComponent {
2   render() {
3     console.log('child render')
4     return <div>child</div>;
5   }
6 }

你會發現它和上圖的Child組件是一樣的效果,同樣只輸出了:

parent render

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM