zhouzhongyuan / qa

Questions recods
MIT License
5 stars 1 forks source link

PureComponent是什么? #43

Open zhouzhongyuan opened 7 years ago

zhouzhongyuan commented 7 years ago

1.概念来源

来源于pure function。

A pure function is a function where the return value is only determined by its input values, without observable side effects.

①不改变input ②类似数学中函数y=f(x), x确定,y就唯一确定。

2.概念

React.PureComponent is exactly like React.Component but implements shouldComponentUpdate() with a shallow prop and state comparison.

——react.purecomponent

如何实现shouldComponentUpdate的呢? 大致是这样的

if (this._compositeType === CompositeTypes.PureClass) {
  shouldUpdate = !shallowEqual(prevProps, nextProps) || ! shallowEqual(inst.state, nextState);
}

3.目的

提高React的速度。 此概念是相对于Component提出的。如何提高了速度呢? mount的时候Component中的shouldComponentUpdate始终返回true

更少的VirtualDOM和更少的diff,提高了React的速度。

下图为React更新的示意图,从左到右,update内容逐渐减少。 rendering-process

4.什么不是PureComponent

class FullName extends Component {
  render() {
    const { firstName, lastName } = this.props;

    return (
      <div>{firstName} {lastName} - {new Date}</div>
    )
  }
}

遗留问题

参考文献