共计 831 个字符,预计需要花费 3 分钟才能阅读完成。
Component
和 PureComponent
最大的不同是 PureComponent
通过 shouldComponentUpdate()
来比拟 prop
和state
的新旧值,从而决定是是否更新组件,当然这里的比拟是浅比拟(shallowEqual
),这里贴一段实现 PureComponent
的代码:
import React, {Component} from 'react'
export default class PureComponent extends Component {shouldComponentUpdate(nextProps, nextState) {
return (!shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState)
)
}
}
function shallowEqual(obj1, obj2) {if (obj1 === obj2) return true
if (
obj1 === null ||
obj2 === null ||
typeof obj1 !== 'object' ||
typeof obj2 !== 'object'
) {return false}
let keys1 = Object.keys(obj1)
let keys2 = Object.keys(obj2)
if (keys1.length !== keys2.length) return false
for (let name of keys1) {if (!obj2.hasOwnProperty(name) || obj1[name] != obj2[name]) {return false}
}
return true
}
函数组件也能够用 React.memo
实现 PureComponent
的成果:
function memo(FunComp){
return class extends React.PureComponent{render(){return <FunComp {...this.props} />
}
}
}
正文完