Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PureComponent是什么? #43

Open
zhouzhongyuan opened this issue Apr 1, 2017 · 0 comments
Open

PureComponent是什么? #43

zhouzhongyuan opened this issue Apr 1, 2017 · 0 comments

Comments

@zhouzhongyuan
Copy link
Owner

zhouzhongyuan commented Apr 1, 2017

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

  • 使用了PureComponent之后,通过判断stateprops有没有改变,来决定是否render
  • 如果不需要render,那么VirtualDOM就不会生成,
  • diff就会更快(因为需要比较的东西少了啊)。

更少的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>
    )
  }
}

遗留问题

  • context对PureComponent有什么影响?

参考文献

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant