介绍几种方法可以加快你的React应用。
一.使用生产版本
默认情况下,React包含很多在开发过程中很有帮助的警告。然而,这会导致React更大更慢。因此,在部署应用时,确认使用了生产版本。
最好在开发应用时使用开发模式,部署应用时换为生产模式。
二. 避免重新渲染
可以通过重写生命周期函数 shouldComponentUpdate
来优化性能,这是在重新渲染过程开始之前触发的。该函数的默认实现中返回的是true
,使得 React 执行更新操作:
shouldComponentUpdate(nextProps, nextState) {
return true;
}
如果在某些情况下你的组件不需要更新,name你可以在shouldComponentUpdate
返回false
来跳过整个渲染过程,包括这个组件和后面调用的render()。
三. 使用shouldComponentUpdate
例子:
如果你想要你的组件仅当 props.color
或 state.count
发生改变时需要更新,你可以通过 shouldComponentUpdate
函数来检查:
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
但是同时React提供了一个helper实现上面的逻辑,继承React.PureComponent。因此下面代码是一种更简单的方式实现了相同功能:
class CounterButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {count: 1};
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
大多数情况下,可以使用React.PureComponent,但是如果存在更复杂的数据结构,可能会出现问题。例如当你像一个list里添加(push)item的时候,代码是不会执行的。因为虽然数组中的值发生了改变,但是新的list和旧的list的值是相同的,所以不会进行更新。
不可变数据的力量
避免这类问题最简单的方法是不要突变(mutate) props 或 state 的值。上述添加item的方法可以通过使用 concat 重写:
handleClick() {
this.setState(prevState => ({
words: prevState.words.concat(['marklar'])
}));
}
或者用ES6对于数组支持展开语法,使得解决上述问题更加方便。
handleClick() {
this.setState(prevState => ({
words: [...prevState.words, 'marklar'],
}));
};
网友评论