react-bits:shouldComponentUpdate() check

前端之家收集整理的这篇文章主要介绍了react-bits:shouldComponentUpdate() check前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

使用shouldComponentUpdate避免昂贵的重复渲染
react组件的props和state改变时会触发重复渲染,每次改变重新渲染整个页面会对浏览器造成很大负担。render之前会触发shouldComponentUpdate,手动判断props和state是否改变,并返回true或false,返回false不会触发渲染。

bad

  1. const AutocompleteItem = (props) => {
  2. const selectedClass = props.selected === true ? "selected" : "";
  3. var path = parseUri(props.url).path;
  4. path = path.length <= 0 ? props.url : "..." + path;
  5.  
  6. return (
  7. <li
  8. onMouseLeave={props.onMouseLeave}
  9. className={selectedClass}>
  10. <i className="ion-ios-eye"
  11. data-image={props.image}
  12. data-url={props.url}
  13. data-title={props.title}
  14. onClick={props.handlePlanetViewClick}/>
  15. <span
  16. onMouseEnter={props.onMouseEnter}
  17. >
  18. <div className="dot bg-mint"/>
  19. {path}
  20. </span>
  21. </li>
  22. );
  23. };

good

  1. export default class AutocompleteItem extends React.Component {
  2. shouldComponentUpdate(nextProps,nextState) {
  3. if (
  4. nextProps.url !== this.props.url ||
  5. nextProps.selected !== this.props.selected
  6. ) {
  7. return true;
  8. }
  9. return false;
  10. }
  11.  
  12. render() {
  13. const {props} = this;
  14. const selectedClass = props.selected === true ? "selected" : "";
  15. var path = parseUri(props.url).path;
  16. path = path.length <= 0 ? props.url : "..." + path;
  17.  
  18. return (
  19. <li
  20. onMouseLeave={props.onMouseLeave}
  21. className={selectedClass}>
  22. <i className="ion-ios-eye"
  23. data-image={props.image}
  24. data-url={props.url}
  25. data-title={props.title}
  26. onClick={props.handlePlanetViewClick}/>
  27. <span
  28. onMouseEnter={props.onMouseEnter}>
  29. <div className="dot bg-mint"/>
  30. {path}
  31. </span>
  32. </li>
  33. );
  34. }
  35. }

猜你在找的React相关文章