鍍金池/ 問答/HTML5  HTML/ PureComponent的用法是不是這樣

PureComponent的用法是不是這樣

一開始學(xué)習(xí)react的時(shí)候看到的是PureRenderMixin 后來google后說是用PureComponent 。我想知道什么時(shí)候用

class App extends React.Component

什么時(shí)候用

class App extends PureComponent 

這兩種寫法出來的組件一個(gè)樣么。 還有這個(gè)PureComponent 我就這么用就可以了?不需要再寫其他的代碼了么

回答
編輯回答
苦妄

PureComponent的本質(zhì)是幫你寫了一個(gè)shouldComponentUpdate,做一層淺比較,實(shí)現(xiàn)渲染時(shí)優(yōu)化。
如果是簡單類型的比較,就不用自己寫shouldComponentUpdate了。
需要注意的是:PureComponent和shouldComponentUpdate不能共存

2017年4月10日 16:12
編輯回答
我甘愿

簡單的說就是purecomponents自己實(shí)現(xiàn)了shouldComponentUpdate 類似下面

function shouldComponentUpdate(nextProps, nextState){
    const cProps = this.props, cState = this.state;
    for(let key in nextProps){
        if(cProps[key] !== nextProps[key]) return true
    }
    for(let key in nextState){
        if(cState[key] !== nextState[key]) return true
    }
    
    return false;
}
2018年3月9日 07:54
編輯回答
晚風(fēng)眠
import React from 'react';

class A extends React.Component {
    //當(dāng)參數(shù)為復(fù)合數(shù)據(jù)組件時(shí),比如對象、數(shù)組、Set、Map等, 以及它們的組件
}

class B extends React.PureComponent {
    //當(dāng)參數(shù)為基本數(shù)據(jù)時(shí)使用,比如String, Number, Boolean等。
}
2017年6月8日 07:49