三羊

三羊的小站

阅读react源码--component部分

May 09, 2017/「 react / Edit on Github ✏️

今天主要看下React.Component,实际上ComponentReact对象上一个构造函数。 构造函数接受三个参数,propscontextupdaterupdater实际是在render中注入的,它是用来实际更新state

function ReactComponent(props, context, updater) {
  this.props = props
  this.context = context
  // emptyObject 是一个空对象{}
  this.refs = emptyObject
  // ReactNoopUpdateQueue is the abstract API for an update queue
  this.updater = updater || ReactNoopUpdateQueue
}

Component 的原型对象上有这么几个属性,分别是isReactComponentsetStateforceUpdateisMountedreplaceState。其中,isMountedreplaceState不推荐使用了,后续版本会移除的。

  • isReactComponent是一个空对象。
ReactComponent.prototype.isReactComponent = {}
  • setState()方法,改变组件state时应该总是使用这个方法,把state看成一个不可变对象。当调用setState()方法时,不会保证立即执行setState函数,也不会立即改变state对象,因为它的执行是一个异步的。它可以有两个参数,第一个参数是对象或者函数,这个函数返回一个对象,第二个参数是一个callback,当setState实际执行完成时会回调这个callback
ReactComponent.prototype.setState = function(partialState, callback) {
  !(
    typeof partialState === "obejct" ||
    typeof partialState === "function" ||
    partialState == null
  )
    ? "警告或者直接报错....."
    : void 0
  // 将当前更新入队
  this.updater.enqueueSetState(this, partialState)
  if (callback) {
    // 将当前callback入队
    this.updater.enqueueCallback(this, callback, "setState")
  }
}
  • forceUpdate()方法,强制更新,谨慎使用,当你知道某些深成次的state已经发生变化了,但没有调用setState()时,你可以调用forceUpdate()。调用forceUpdate()不会触发shouldComponent,会触发componentWillUpdatecomponentDidUpdate方法。
ReactComponent.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this)
  if (callback) {
    this.updater.enqueueCallback(this, callback, "forceUpdate")
  }
}

再来看一下PureComponent,它与Component结构一样,只不过在其原型对象上增加一个isPureComponent=true的属性。

function ComponentDummy() {}
ComponentDummy.prototype = ReactComponent.prototype
ReactPureComponent.prototype = new ComponentDummy()
ReactPureComponent.prototype.constructor = ReactPureComponent
// Avoid an extra prototype jump for these methods.
_assign(ReactPureComponent.prototype, ReactComponent.prototype)
ReactPureComponent.prototype.isPureReactComponent = true

「react 版本 15.5.4」

若有收获,小额鼓励