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)
}
}