React.Component、React.PureComponent、React.FC的使用與區別

1. React.Component

最常見的,包含最常用的render(),componentDidMount(),shouldComponentUpdate…

  • shouldComponentUpdate(nextProps, nextState)
    判斷 React 組件的輸出是否受當前 state 或 props 更改的影響。意思就是隻要組件的 props 或者 state 發生了變化,就會重新構建 virtual DOM,然後使用 diff算法進行比較,再接着根據比較結果決定是否重新渲染整個組件。shouldComponentUpdate函數是重渲染時render()函數調用前被調用的函數,它接受兩個參數:nextProps和nextState,分別表示下一個props和下一個state的值。並且,當函數返回false時候,阻止接下來的render()函數的調用,阻止組件重渲染,而返回true時,組件照常重渲染。
  • React.Component 並未實現 shouldComponentUpdate(),如何利用shouldComponentUpdate鉤子函數優化react性能
  • demo1.tsx
import React, { PureComponent,Component } from 'react';
class CompareComponent extends Component<any, any>{
 state = {
   isShow: false,
   count:1
 }
 shouldComponentUpdate(nextProps, nextState){
   if(nextState.isShow===this.state.isShow){
     return false // false則不會調用render
   }
   return true
 }
 changeState = () => {
   this.setState({
     isShow: true
   })
 };

 handleAdd=()=>{
   const {count} = this.state
   this.setState({
     count:count+1
   })
 }

 render() {
   console.log('render');
   return (
     <div>
       <button onClick={this.changeState}>點擊賦值</button>
       <div>{this.state.isShow.toString()}</div>

       <button onClick={this.handleAdd}>點擊{this.state.count}</button>
     </div>
   );
 }
}
export default CompareComponent

參考鏈接

2.React.PureComponent

React.PureComponent 與 React.Component 幾乎完全相同,也包括render,生命週期等等。但 React.PureComponent 通過props和state的淺對比來實現 shouldComponentUpate()。如果對象包含複雜的數據結構,它可能會因深層的數據不一致而產生錯誤的否定判斷(表現爲對象深層的數據已改變視圖卻沒有更新

  • React.PureComponent在某些條件下,render不用重新渲染
  • PureComponent中不能有shouldComponentUpdate
  • demo2.tsx
import React, { PureComponent,Component } from 'react';

class CompareComponent extends PureComponent{
  state = {
    isShow: false,
    count:1
  }
  changeState = () => {
    this.setState({
      isShow: true
    })
  };
  handleAdd=()=>{
    const {count} = this.state
    this.setState({
      count:count+1
    })
  }
  render() {
    console.log('render');
    return (
      <div>
        <button onClick={this.changeState}>點擊賦值</button>
        <div>{this.state.isShow.toString()}</div>

        <button onClick={this.handleAdd}>點擊{this.state.count}</button>
      </div>
    );
  }
}
export default CompareComponent

3.React.Component、React.PureComponent的區別

通過查看render的渲染次數會發現規律
shouldComponentUpdate返回true的話,React.Component無論state發生新的改變,都會重新渲染render。若是返回false,則state在滿足條件下返回false的話,不會重新渲染render

  • PureComponent = shouldComponentUpdate(false) + React.Component

4.React.FC

React.FC<>的在typescript使用的一個泛型,這個泛型裏面可以使用useState
這個裏面無生命週期。
useState在前兩者中不能使用,只能在函數組件或者泛型裏面使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章