@H_404_1@使用shouldComponentUpdate避免昂贵的重复渲染
react组件的props和state改变时会触发重复渲染,每次改变重新渲染整个页面会对浏览器造成很大负担。render之前会触发shouldComponentUpdate,手动判断props和state是否改变,并返回true或false,返回false不会触发渲染。 @H_404_1@bad
原文链接:/react/304194.htmlreact组件的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>
);
}
}