react的性能優(yōu)化

1.shouldComponentUpdate

控件組件自身或者子組件是否需要更新,尤其是在子組件非常多的情況下,需要進(jìn)行優(yōu)化。

 shouldComponentUpdate(nextProps, nextState) {
        if (JSON.stringify(this.state.text) !== JSON.stringify(nextState.text)) {
            return true
        }
        return false
       
    }

2.PureComponent

pureComponent 會(huì)幫你 比較新props跟舊的props,新的state 和老的 state(值相等,或者對(duì)象含有相同的屬性 且屬性值相等),決定shouldcomponentUpdate 返回true 或者 false,從而決定要不要呼叫 render function
//注意 如果你的state 或 props [永遠(yuǎn)都會(huì)變],那PureComponent 并不會(huì)比較快,因?yàn)閟hallowEqual 也需要花時(shí)間


import React, { PureComponent } from 'react'
export default class app extends PureComponent {
    state = {
        mytext:"11111"
    }
    render() {
      console.log('render')
    return (
        <div>
            <button onClick={() => this.setState({mytext:"2222"})}>click</button>
            {this.state.mytext}
      </div>
    )
    }
    getSnapshotBeforeUpdate() {
        console.log("getSnapshotBeforeUpdate")
        return 111;
    }

    componentDidUpdate(prevProps, prevState,value) {
        console.log("componentDidUpdate",value)
    }
   
}
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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