在React中,默认情况下,如果父组件数据发生了更新,那么所有子组件都会无条件更新 !!!!!!
通过shouldComponentUpdate()
retrun fasle 来判断阻止 Header 组件做无意义的更新shouldComponentUpdate()
并不是每次都需要使用,而是需要的时候才会优化
class App extends React.Component {
constructor () {
this.state = { list: [] }
}
render () {
return (
<div>
{/* 当list数据发生变化时,Header组件也会更新,调用 render() */}
<Header />
<List data={this.state.list}
</div>
)
}
}
在shouldComponentUpdate()
判断中,有一个有意思的问题,解释为什么 React setState()
要用不可变值
**
// 父组件中
changeList () {
this.state.list.push({id: 2})
this.setState({
list: this.state.list
})
}
// 子组件中
import _ from 'lodash'
shouldComponentUpdate(nextProps, nextState) {
// 数组深度比较(一次性递归到底,耗费性能,工作中慎用)深比较
if (_.isEqual(nextProps.list, this.props.list)) {
return false // 相等,不渲染
}
return true // 不相等,渲染
}
PureComponent & memo
- class类组件中用
PureComponent
,无状态组件(无状态)中用memo
- PureComponent, SCU中实现了浅比较
- 浅比较已使用大部分情况(尽量不要做深度比较)
PureComponent 与普通 Component 不同的地方在于,PureComponent自带了一个shouldComponentUpdate()
,并且进行了浅比较
// memo用法
function MyComponent (props) {
/* 使用 props 渲染 */
}
// areEqual 也可不传
function areEqual(prevProps, nextProps) {
if (prevProps.seconds===nextProps.seconds) {
return true
} else {
return false
}
}
export default React.memo(MyComponent, areEqual)