REACT的优化
1. 使用PureComponent
PureComponent控件和Component的区别是:
在shouldComponentUpldate中实现了一个浅比较的功能。
import React, { PureComponent } from 'react';
class PreviewList extends PureComponent {
constructor(props) {
super(props);
this.state = {
value: 0,
};
}
addValue=() => {
this.setState(preState => ({ value: preState.value + 1 }));
};
// 重置value值,测试PureComponent的浅比较功能
reInputSameValue=() => {
this.setState(preState => ({ value: preState.value }));
}
render() {
console.log('render 被调用');
const { value } = this.state;
return (
<div>
PreviewList
{value}
<button type="button" onClick={this.reInputSameValue}>重置数字</button>
<button type="button" onClick={this.addValue}>增加数字</button>
</div>
);
}
}
export default PreviewList;
可以看见由于浅比较功能,value虽然被设置了相同的值但是render并没有被执行。
下面看看设置object参数试试(这里考察深比较)
import React, { PureComponent } from 'react';
class PreviewList extends PureComponent {
constructor(props) {
super(props);
this.state = {
value: 0,
complexValue: { info: 'hello' },
};
}
addValue=() => {
this.setState(preState => ({ value: preState.value + 1 }));
};
// 重置value值,测试PureComponent的浅比较功能
reInputSameValue=() => {
this.setState(preState => ({ value: preState.value }));
}
// 重置object类型值,用于测试PureComponent在需要深比较功能时的表现
reInputSameObjectValue=() => {
this.setState(preState => ({ complexValue: Object.assign({}, preState.complexValue) }));
}
render() {
console.log('render 被调用');
const { value, complexValue } = this.state;
return (
<div>
PreviewList
{value}
{complexValue.info}
<button type="button" onClick={this.reInputSameValue}>重置数字</button>
<button type="button" onClick={this.reInputSameObjectValue}>重置复杂对象</button>
<button type="button" onClick={this.addValue}>增加数字</button>
</div>
);
}
}
export default PreviewList;
console: render 被调用 (*n)
可见PureComponent对复杂属性没有作用
2. Deep Compare
深比较,深比较会增加性能损失,请自己权衡后使用。
import React, { Component } from 'react';
import { isEqual } from 'lodash';
class DeepCompareDemo extends Component {
constructor(props) {
super(props);
this.state = {
complexValue: { info: 'hello' },
};
}
//facebook--react推荐使用loadsh.isEqual进行深比较
shouldComponentUpdate=(nextProps, nextState) => {
console.log(isEqual(this.state, nextState));
if (!isEqual(nextProps, this.props) || !isEqual(this.state, nextState)) {
return true;
}
return false;
};
// 重置object类型值,用于测试PureComponent在需要深比较功能时的表现
reInputSameObjectValue=() => {
this.setState(preState => ({ complexValue: Object.assign({}, preState.complexValue, { info: 'hello2' }) }));
};
render() {
console.log('render 被调用');
const { complexValue } = this.state;
return (
<div>
{complexValue.info}
<br />
<button type="button" onClick={this.reInputSameObjectValue}>重置复杂对象</button>
</div>
);
}
}
export default DeepCompareDemo;
本人测试了一下(参考:查看react性能情况),本例子的isEqual消耗了1.33~0.22ms的时间,虽然本例子耗时不多,但是考虑到多个控件叠加的情况,很可能造成卡顿请酌情使用。