React基于prop和state的diff来决定是否要重新render组件。如果你知道在某些情况下不需要更新组件,可以在shouldComponentUpdate返回false来跳过render。例如:
// 仅当 props.color 或 state.count 发生改变时需要更新 shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; } return false; }
React.PureComponent可以对props和state的所有属性进行浅比较,来决定组件是否需要更新。
class CounterButton extends React.PureComponent { ... }
多数情况下,可以使用React.PureComponent,而不是自己写shouldComponentUpdate。但React.PureComponent仅会进项浅比较,在更新数组和对象时要注意。
如果只是局部更新数组或对象属性值,浅比较时会认为新旧值一样,没发生变化导致不重新render。所以更新数组或对象时,最好用ES6的展开语法:
this.setState(state => ({ words: [...state.words, 'marklar'], color: {...state.color, right: 'blue'}; }));