Skip to content
On this page

Component 和 PureComponent

PureComponent相比较于Component,自动增加shouldComponentUpdate周期函数,并对原始属性/状态和最新属性/状态进行浅比较!

  • 当属性和状态没有任何改变的情况下,是不会进行组件更新的,起到一个优化的作用!
  • forceUpdate强制更新时,会跳过内部设置的shouldComponentUpdate函数
JavaScript
export default class Demo extends React.Component {
    state = {
        arr: [10, 20, 30]
    };
    handler = () => {
        this.state.arr.push(40);
        this.setState({ arr: this.state.arr });
    };
    render() {
        return <div className="demo">
            {this.state.arr.join('+')}
            <button onClick={this.handler}>更改</button>
        </div>;
    }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

自动增加shouldComponentUpdate周期函数,并对原始属性/状态和最新属性/状态进行浅比较

JavaScript
const shallowEqual = function shallowEqual(objA, objB){
  if (Object.is(objA, objB))  return true;
  if (typeof objA !== 'object' || objA === null ||
      typeof objB !== 'object' || objB === null) {
    return false;
  }
  const keysA = Reflect.ownKeys(objA),
        keysB = Reflect.ownKeys(objB);
  if (keysA.length !== keysB.length) return false;
  for (let i = 0; i < keysA.length; i++) {
    let key = keysA[i];
    if (
      !objB.hasOwnProperty(key) ||
      !Object.is(objA[key], objB[key])
    ) {
      return false;
    }
  }
  return true;
};

// 测试使用
export default class Demo extends React.Component {
    ...
    shouldComponentUpdate(nextProps, nextState) {
        return !shallowEqual(this.props, nextProps) ||
            !shallowEqual(this.state, nextState);
    }
    ...
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
沪ICP备20006251号-1