在《深入React技术栈中》有一个关于react性能优化的方案,原文如下
(原书P106-P107 2.6组件性能优化):
前面已经介绍过,React 做性能优化时最常用的就是 shouldComponentUpdate 方法,但它默认返回 true,即始终会执行 render 方法,然后做 Virtual DOM 比较,并得出是否需要做真实 DOM 的更新,这里往往会带来很多没必要的渲染。当然,我们也可以在 shouldComponentUpdate 中使用深拷贝和深比较来避免无必要的 render, 但深拷贝和深比较一般都是非常昂贵的选。
Immutable.js 则提供了简洁、高效的判断数据是否变化的方法,只需 === 和 is 比较就能知 道是否需要执行 render , 而这个操作几乎零成本, 所以可以极大提高性能。 修改后的 shouldComponentUpdate 是这样的:
import React, { Component } from "react";
import { is } from "immutable";
class App extends Component {
shouldComponentUpdate(nextProps, nextState) {
const thisProps = this.props || {};
const thisState = this.state || {};
if (
Object.keys(thisProps).length !== Object.keys(nextProps).length ||
Object.keys(thisState).length !== Object.keys(nextState).length
) {
return true;
}
for (const key in nextProps) {
if (
nextProps.hasOwnProperty(key) &&
!is(thisProps[key], nextProps[key])
) {
return true;
}
}
for (const key in nextState) {
if (
nextState.hasOwnProperty(key) &&
!is(thisState[key], nextState[key])
) {
return true;
}
}
return false;
}
}
我在想,作者为什么要搞的这么复杂呢,像下面这样岂不是更加简单:
import React, { Component } from "react";
import { is } from "immutable";
class App extends Component {
shouldComponentUpdate(nextProps, nextState) {
const thisProps = this.props || {};
const thisState = this.state || {};
if (is(thisProps, nextProps) && is(thisState, nextState)) {
return false
} else {
return true
}
}
}
请大神指教,我的方法有什么缺陷,原作者的方法有什么优势