关于render渲染优化
除初始化组件渲染外,组件会在以下两种情况下发生重渲染:
1、当调用setState()函数时,组件会发生重渲染,即使组件的state未发生改变;
2、当父组件发生重渲染时,其全部子组件都会重渲染。
在父组件中通过调用异步函数修改了某一参数值,将其传递给子组件后,在子组件的componentDidMount()函数中获取到的仍然是未修改之前的值:原来父组件传递的参数改变后,子组件会重新渲染的只有render函数
虽然React的重渲染机制是严谨的,但是也是非常耗时的,我们有两种方式来阻止组件不必要的重渲染。
shouldComponentUpdate(nextProps,nextState)
shouldComponentUpdate(nextProps,nextState )是重渲染时render函数调用之前被调用的函数,它接收两个参数:nextProps和nextState,分别表示下一个props和下一个state的值,并且,当函数返回false时,阻止接下来的render()函数的调用,阻止组件重渲染,而返回true时,组件照常重渲染,React默认返回true。
import React from 'react'; class Test extends React.Component {
constructor(props) {
super(props);
this.state = {
strTest: "render测试" //设state中strTest值
}
}
//这里调用了setState但是并没有改变setState中的值
handleClick = () => {
const prestrTest = this.state.strTest;
this.setState({
prestrTest: this.state.strTest
})
}
//在render函数调用前判断:如果前后state中的内容不变,通过return false阻止render调用
shouldComponentUpdate (nextProps, nextState) {
if (nextState.strTest == this.state.strTest) {
return false
}
}
render () {
//当render函数被调用时,打印当前的strTest
console.log(this.state.strTest)
return (
<h1 onClick={this.handleClick}>
{this.state.strTest}
</h1>)
}
}
export default Test;
PureComponet
PureComponet原理:只需要把组件的继承类从Component换成PureComponent即可。PureComponent 自动加载了shouldComponentUpdate 函数,当组件更新时,shouldComponentUpdate 对props和state进行了一层浅比较,如果组件的props和state都没有发生改变,render方法就不会触发,省去Virtual DOM的生成和对比过程,达到提升性能的目的。
但是由于PureComponent对props和state只进行了浅比较,所以对与嵌套的对象并不适用。
render渲染优化
- 属性传递优化
- 比较this绑定五种方法的性能
- 父向子传递对象时,应将其先定义再使用
- 在传递props/state时,只传递需要的参数
- shouldComponentUpdate(nextProps,nextState):比较值未改变时,阻止render
- PureComponet:自动加载了shouldComponentUpdate 函数,进行浅比较,故不适用于嵌套的对象
网友评论