react-bits:shouldComponentUpdate() check

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

bad

const AutocompleteItem = (props) => {
  const selectedClass = props.selected === true ? "selected" : "";
  var path = parseUri(props.url).path;
  path = path.length <= 0 ? props.url : "..." + path;

  return (
    
  • .onMouseLeave} className={selectedClass}> "ion-ios-eye" data-image={props.image} data-url={props.url} data-title={props.title} onClick={props.handlePlanetViewClick}/> .onMouseEnter} >
    "dot bg-mint"/> {path}
  • ); };

    good

    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 (
          
  • "ion-ios-eye" data-image={props.image} data-url={props.url} data-title={props.title} onClick={props.handlePlanetViewClick}/> <div className="dot bg-mint"/> {path}
  • ); } }

    你可能感兴趣的:(web前端,react-bits)