提示:记得点关注哦!
提示:以下是本篇文章正文内容
一、shouldComponentUpdate介绍?
shouldComponentUpdate(nextProps,nextState)
- nextProps:表示下一个props
- nextState:表示下一个state的值
- shoudldComponentUpdate()的返回值,判断React组件的输出是否受到当前的state或props更改的影响,默认行为使state每次发生变化组件都会重新渲染
shouldComponentUpdate(nextProps, nextState){
//组件是否需要更新,需要返回一个布尔值,返回true则更新,返回flase不更新,这是一个关键点
console.log('shouldComponentUpdate组件是否应该更新,需要返回布尔值',nextProps, nextState)
return true
}
注:当props或state发生变化时,shouldComponentUpdate会在渲染执行之前被调用,返回值默认为true,首次渲染或使用forceUpdate时不会调用该方法。
二、性能优化
React提供了生命周期函数shouldComponentUpdate()
,根据它的返回值(true | false),判断 React 组件的输出是否受当前 state 或 props 更改的影响。默认行为是 state 每次发生变化组件都会重新渲染。
shouldComponentUpdate
方法接收两个参数nextProps
和nextState
,可以将this.props与nextProps以及this.state与nextState进行比较,并返回 false 以告知 React 可以跳过更新。
shouldComponentUpdate (nextProps, nextState) {
return true
}
此时我们已经知道了shouldComponentUpdate
函数的作用,下面我们在Child组件中添加以下代码:
shouldComponentUpdate(nextProps, nextState) {
return this.props.son !== nextProps.son
}
这个时候再点击按钮修改父组件 state 中的parentInfo的值时,Child组件就不会再重新渲染了。
注意:我们从父组件Parent向子组件Child传递的是基本类型
的数据,若传递的是引用类型
的数据,我们就需要在shouldComponentUpdate
函数中进行深层比较。但这种方式是非常影响效率,且会损害性能的。所以我们在传递的数据是基本类型是可以考虑使用这种方式(即:this.props.son !== nextProps.son
)进行性能优化。
总结
1、类组件中shouldComponentUpdate() 和 React.PureComponent 在基本类型数据传递时都可以起到性能优化
作用,当包含引用类型数据传递的时候,shouldComponentUpdate()更合适一些
。