react-bits:shouldComponentUpdate() check

前端之家收集整理的这篇文章主要介绍了react-bits:shouldComponentUpdate() check前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_404_1@使用shouldComponentUpdate避免昂贵的重复渲染
react组件的props和state改变时会触发重复渲染,每次改变重新渲染整个页面会对浏览器造成很大负担。render之前会触发shouldComponentUpdate,手动判断props和state是否改变,并返回true或false,返回false不会触发渲染。

@H_404_1@bad

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

  return (
    <li
      onMouseLeave={props.onMouseLeave}
      className={selectedClass}>
      <i className="ion-ios-eye"
         data-image={props.image}
         data-url={props.url}
         data-title={props.title}
         onClick={props.handlePlanetViewClick}/>
      <span
        onMouseEnter={props.onMouseEnter}
      >
        <div className="dot bg-mint"/>
        {path}
      </span>
    </li>
  );
};
@H_404_1@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 (
      <li
        onMouseLeave={props.onMouseLeave}
        className={selectedClass}>
        <i className="ion-ios-eye"
           data-image={props.image}
           data-url={props.url}
           data-title={props.title}
           onClick={props.handlePlanetViewClick}/>
        <span
          onMouseEnter={props.onMouseEnter}>
          <div className="dot bg-mint"/>
          {path}
        </span>
      </li>
    );
  }
}
原文链接:/react/304194.html

猜你在找的React相关文章