React類元件效能優化之shouldComponentUpdate、React.PureComponent
阿新 • • 發佈:2020-12-30
前言
這兩個效能優化方法是對與類元件來說的。有些時候我們setState時,狀態值並沒有改變,但是相關的元件還是渲染了。比如如下程式碼的執行
class Test extends React.Component {
state = {
value:0
}
componentWillUpdate() {
console.log('Test 渲染了')
}
render() {
return <div>
{this.state. value}
<button onClick={()=>{this.setState({value:1})}}>changeValue</button>
<Testson />
</div>
}
}
class Testson extends React.Component {
componentWillUpdate() {
console.log('Testson 渲染了')
}
render() {
return < p>76485768</p>
}
}
點選changeValue後會渲染一次,因為state的狀態值改變了。元件會重新渲染。這時value的值為1。但是我們再點一次changeValue時,state的值並沒有改變,還是1。元件渲染了。
為了提升效能,我們應該避免不必要的渲染。
shouldComponentUpdate
- nextProps: 元件將會接收的下一個引數props
- nextProps: 元件的下一個狀態state
shouldComponentUpdate(nextProps, nextState) {
return true
}
返回true時元件會渲染,如果時false則不會渲染;
以上的元件可以這樣優化
class Test extends React.Component {
state = {
value:0
}
componentWillUpdate() {
console.log('Test 渲染了')
}
shouldComponentUpdate(nextProps,nextState) {
if(this.state.value === nextState.value){
return false
}else{
return true
}
}
render() {
return <div>
{this.state.value}
<button onClick={()=>{this.setState({value:1})}}>changeValue</button>
<Testson />
</div>
}
}
這樣就不會多次渲染了
React.PureComponent
這個相對於的是react函式元件的React.memo()的效能優化。
class Test extends React.PureComponent {
state = {
value:0
}
componentWillUpdate() {
console.log('Test 渲染了')
}
// shouldComponentUpdate(nextProps,nextState) {
// if(this.state.value === nextState.value){
// return false
// }else{
// return true
// }
// }
render() {
return <div>
{this.state.value}
<button onClick={()=>{this.setState({value:1})}}>changeValue</button>
<Testson />
</div>
}
}
使用React.PureComponent的效果和shouldComponentUpdate的效果一樣。都是狀態不改變,不會重複渲染。