提高性能可分为两方面:
一、配置层面
二、代码层面
本文只从代码层面考虑:
一、避免重复渲染
这里要说一句:
当shouldComponentUpdate返回false的时候不触发render函数也就无法造成渲染
触发render之后react发现原来的dom与现在的dom一致,将不触发更新
如何避免重复渲染呢?
其实就是在shouldComponentUpdate方法中进行if判断,特定条件下才允许返回true
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提供了一个辅助对象来实现这个逻辑 - 继承自React.PureComponent,当state中的值改变的时候才可以触发render。但要注意,这里仅仅是浅比较。
如果需要进行深比较,那么有两种方法
一、创建新的对象,然后进行setstate操作(推荐理由:完全不需要再引一个库吧)
function updateColorMap(colormap) { return Object.assign({}, colormap, {right: 'blue'}); }
this.setState(prevState => ({ words: prevState.words.concat(['marklar']) }));
二、使用不可突变的数据结构Immutable.js
参考:https://reactjs.org/docs/optimizing-performance.html