React中Component和PureComponnt組件的區(qū)別

兩種組件的聲明方式,都可以創(chuàng)建React組件
import React,{Component,PureComponent} from 'react'
class A extends Component{
//....
}

class B extends PureComponent{
//...
}

區(qū)別:

兩種聲明組件的方式區(qū)別不大,最主要的區(qū)別就是shouldComponentUpdate鉤子函數(shù)是否可以使用

  • Component組件內(nèi), 當(dāng)props或state發(fā)生變化時(shí), 會(huì)取決于shouldComponentUpdate()函數(shù)返回的值 來決定是否會(huì)重新渲染組件,true渲染 false不渲染,。當(dāng)父組件的state或props更新時(shí),無論子組件的props和state是否更新 都會(huì)重新渲染子組件, 這樣會(huì)有性能消耗。
  • PureComponent組件內(nèi),不可使用shouldComponentUpdate鉤子函數(shù),組件是否重新渲染會(huì)自動(dòng)判斷props和state是否發(fā)生變化, 淺比較:對(duì)于引用類型的數(shù)據(jù),只比較變量的地址是否改變。對(duì)比之后 沒有變化不渲染。

下面寫一個(gè)例子來實(shí)踐一下

import React, { PureComponent } from 'react';
class AddModal extends PureComponent<IProps, State> {
  state = {
    arr: [1,2,3,4,5],
  };
  
handleClick = () => {
    const { arr } = this.state
    arr.pop();
    this.setState({
      arr,
    })
}

render(){
  const { arr } = this.state
  return <div>
      <button onClick={this.handleClick}>click</button>
      <p>arr</p>
  </div>
}
// 頁面最初展示的是 12345
// 當(dāng)我們點(diǎn)擊按鈕之后 頁面并沒有變化 展示的還是12345
}
  • Component
import React from 'react';
class AddModal extends React.Component<IProps, State> {
  state = {
    arr: [1,2,3,4,5],
  };
  
handleClick = () => {
    const { arr } = this.state
    arr.pop();
    this.setState({
      arr,
    })
}

render(){
  const { arr } = this.state
  return <div>
      <button onClick={this.handleClick}>click</button>
      <p>arr</p>
  </div>
}
// 頁面最初展示的是 12345
// 當(dāng)我們點(diǎn)擊按鈕之后 頁面發(fā)生變化 展示的是1234
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容