- shouldComponentUpdate检查
- 坏实践
- 好实践
- 参考资料:
shouldComponentUpdate检查
合理的实现shouldComponentUpdate能够避免不必要的重新渲染.
React会在props和state发生改变的时候重新渲染组件.
试想一下当每次有props和state发生改变时(可能只是一个很小的用户动作), 整个页面都会重新渲染一次, 这从性能上来说肯定不能令人满意. 这就是shouldComponentUpdate这个生命周期函数发挥作用的时候了. 当React想要重新渲染组件时, React会检查shouldComponentUpdate这个函数是返回true还是false(这将决定组件是否更新.)React默认这个函数是返回true的,意味着无论state还是props发生变化, 组件都将被更新). 所以对于那些不需要变化的组件, 我们可以直接返回false来阻止组件更新,以此提升性能. 但更多的时候, 我们需要在这个函数内写自己的逻辑来判断组件是否需要更新.
坏实践
const AutocompleteItem = (props) => {const selectedClass = props.selected === true ? "selected" : "";var path = parseUri(props.url).path;path = path.length <= 0 ? props.url : "..." + path;return (<lionMouseLeave={props.onMouseLeave}className={selectedClass}><i className="ion-ios-eye"data-image={props.image}data-url={props.url}data-title={props.title}onClick={props.handlePlanetViewClick}/><spanonMouseEnter={props.onMouseEnter}><div className="dot bg-mint"/>{path}</span></li>);};
好实践
export default class AutocompleteItem extends React.Component {shouldComponentUpdate(nextProps, nextState) {if (nextProps.url !== this.props.url ||nextProps.selected !== this.props.selected) {return true;}return false;}render() {const {props} = this;const selectedClass = props.selected === true ? "selected" : "";var path = parseUri(props.url).path;path = path.length <= 0 ? props.url : "..." + path;return (<lionMouseLeave={props.onMouseLeave}className={selectedClass}><i className="ion-ios-eye"data-image={props.image}data-url={props.url}data-title={props.title}onClick={props.handlePlanetViewClick}/><spanonMouseEnter={props.onMouseEnter}><div className="dot bg-mint"/>{path}</span></li>);}}
参考资料:
- @nesbtesh/react-performance-optimization-28ec5b61fff3">React Performance optimization
- React rendering misconception
