避免不必要的組件渲染

不要在render的函數(shù)中綁定值

not: <Com onClick={() =>?this.handleClick(param)} />

會(huì)導(dǎo)致每次父組件render方法被調(diào)用時(shí),一個(gè)新的函數(shù)被創(chuàng)建。這會(huì)有一個(gè)改變每個(gè)子組件props的副作用,它將會(huì)造成它們?nèi)恐匦落秩?,即使?shù)據(jù)本身沒有發(fā)生變化。

√ :?<Com? onClick={this.handleClick} param={param} />

子組件中 handleClick() {? ? this.props.onClick(this.props.param)? ? }

不要在render方法里派生數(shù)據(jù)

not : 在render方法中

const?{ datas } =?this.props

const?data = datas.sort( (a, b) =>?b.values - a.values?).slice(0,?9)

每次組件重新渲染時(shí)data都將有一個(gè)新的引用,即使datas沒有改變并且派生數(shù)據(jù)也是相同的。

√ : 緩存派生數(shù)據(jù)

componentWillMount() {? ? this.setDatas( this.props.datas?)? ? }

componentWillReceiveProps(nextProps) {? ? if?(this.props.datas?!== nextProps.datas?) {? ? this.setDatas?(nextProps)? ? }? ? }

setDatas?(datas) {? ? this.setState({? ? datas?: datas.sort( (a, b) =>?b.values?- a.values?).slice(0,?9)? ? })? ? }

最后編輯于
?著作權(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ù)。

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