在react开发中,经常要对数据state状态进行改变,但是这种方式每当setState的时候都会将所有的组件重新渲染一遍,这样就会有重复渲染render的问题,会造成不必要的性能开销
shouldComponentUpdate介绍
shouldComponentUpdate(nextProps, nextState)
- nextProps: 表示下一个props
- nextState: 表示下一个state的值
使用shouldComponentUpdate就是为了减少render不必要的渲染。返回布尔值,然后做Virtual DOM比较,并得出是否需要做真实DOM更新。
import React, { Component } from 'react'
class Title extends Component {
shouldComponentUpdate(nextProps){
// 比较之前的title和传来的title是否相同,如果相同,不重新render; 如果不相同,重新render
return nextProps.title!==this.props.title
}
render() {
console.log("我是title组件")
return (
<div>
标题:{this.props.title}
</div>
)
}
}
class Count extends Component {
render() {
console.log("我是条数组件")
return (
<div>
条数:{this.props.count}
</div>
)
}
}
// Purememo整个组件会重新渲染,如果不使用shouldComponentUpdate那么Title,Count会一直渲染,但是使用shouldComponentUpdate后Title则不会发生渲染。
export default class Purememo extends Component {
constructor(props){
super(props)
this.state={
title:'shouldComponentUpdate使用',
count:0
}
}
componentDidMount(){
setInterval(()=>{
this.setState({
count:this.state.count+1
})
},1000)
}
render() {
return (
<div>
<Title title={this.state.title}></Title>
<Count count={this.state.count}></Count>
</div>
)
}
}
- 如果是进行引用类型的比较(就是对象的地址不变,但是对象里面的值会改变,就无法进行render了)
解决方法:
npm install immutable