PureComponent
和component
相比,PureComponent
通过prop
和state
的浅比较来实现shouldComponentUpdate
,在某些情况下,用PureComponent
可以提高页面的渲染性能。
// shallowEqual 会比较 Object.keys(state | props) 的长度是否一致,每一个 key 是否两者都有,
// 并且是否是一个引用,也就是只比较了第一层的值,确实很浅,所以深层的嵌套数据是对比不出来的
if (this._compositeType === CompositeTypes.PureClass) {
shouldUpdate = !shallowEqual(prevProps, nextProps) || !shallowEqual(inst.state, nextState);
}
当组件状态十分复杂的时候,建议不要去使用PureComponent
。同时PureComponent
的父组件,其子组件也必须是PureComponent
,否正很有可能达不到预期的渲染效果。建议PureComponent
主要用在逻辑简单的展示性子组件中。
import React, { PureComponent } from 'react';
class PureComponentTest extends PureComponent {
constructor(props) {
super(props);
this.state = {
isClick: false,
wordList: []
}
}
handleClick = () => {
this.setState(preState => ({
isClick: !preState.isClick
}))
}
handleAddWordClick = () => {
// concat、ES6的扩展运算符(spread) 的操作不会对元数据产生影响
this.setState(preState => ({
// wordList: preState.wordList.concat(" this ")
wordList: [...preState.wordList," this "]
}))
// 解析赋值两个变量具有相同的引用,指向同一个对象,wordList的push操作同时改变了this.state.wordList的值,
// PureComponent 会对 props 和 state 进行浅层比较,因此两者不会发生改变,从而不会重新渲染
// const { wordList } = this.state;
// wordList.push(" this ")
// this.setState({
// wordList
// })
}
render() {
const { isClick, wordList } = this.state;
return (
<div>
<button onClick={this.handleClick}>点击</button>
<div>{isClick.toString()}</div>
<button onClick={this.handleAddWordClick}>点击增加单词</button>
<div>{wordList.join(",")}</div>
</div>
)
}
}
export default PureComponentTest;