React source React.Component

React most important component is, more components are written in succession to React.Component. Most students will probably think this Component base class provides us with a variety of functions. He helped us to run the render function. Then we write the final rendered inside the label dom or sub-assemblies like. To render our browser into a desired form inside pages. Prior to look at the real source I think so. But after reading the source code found him inside me a perception of him.

 

React in which this one is not the only Component base class. There is another one called PureComponent. The Component him with the only difference is that he offers a simple realization of shouldComponentUpdate. He assured the case of our components without any change in the props can reduce the necessary updates.

 

Import found in the source React.js inside {Component, PureComponent} from './ReactBaseClasses'; Component learned from ReactBaseClasses.js. Open ReactBaseClasses.js. Found Component

 

function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

 

See Component function is a way to declare a class. He accepts three parameters, one is the props, is a context, one is the updater. props and context should be useful to before. In the code which we can see this.props = props, this.context = context. When we use the internal components that can go directly to use. Then continue to declare a this.refs = emptyObject. The students used the string ref React them, you know what is the point of this thing yes. Examples of that node would we want to get his final mount on string ref. The last update is more curious, because we have not had to use this object in React.Component them. Then the object specifically what meaning does, we were going to look down.

 

Component.prototype.isReactComponent = {};

/**
 * Sets a subset of the state. Always use this to mutate
 * state. You should treat `this.state` as immutable.
 *
 * There is no guarantee that `this.state` will be immediately updated, so
 * accessing `this.state` after calling this method may return the old value.
 *
 * There is no guarantee that calls to `setState` will run synchronously,
 * as they may eventually be batched together.  You can provide an optional
 * callback that will be executed when the call to setState is actually
 * completed.
 *
 * When a function is provided to setState, it will be called at some point in
 * the future (not synchronously). It will be called with the up to date
 * component arguments (state, props, context). These values can be different
 * from this.* because your function may be called after receiveProps but before
 * shouldComponentUpdate, and this new state, props, and context will not yet be
 * assigned to this.
 *
 * @param {object|function} partialState Next partial state or function to
 *        produce next partial state to be merged with current state.
 * @param {?function} callback Called after state is updated.
 * @final
 * @protected
 */
Component.prototype.setState = function(partialState, callback) {
  invariant(
    typeof partialState === 'object' ||
      typeof partialState === 'function' ||
      partialState == null,
    'setState(...): takes an object of state variables to update or a ' +
      'function which returns an object of state variables.',
  );
  this.updater.enqueueSetState(this, partialState, callback, 'setState');
};

/**
 * Forces an update. This should only be invoked when it is known with
 * certainty that we are **not** in a DOM transaction.
 *
 * You may want to call this when you know that some deeper aspect of the
 * component's state has changed but `setState` was not called.
 *
 * This will not invoke `shouldComponentUpdate`, but it will invoke
 * `componentWillUpdate` and `componentDidUpdate`.
 *
 * @param {?function} callback Called after update is complete.
 * @final
 * @protected
 */
Component.prototype.forceUpdate = function(callback) {
  this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
};

We see a isReactComponent prototype above Component, he is equal to an empty object. What this thing does not seem particularly useful, on the first skip.

There is then the following method is called the prototype setState. Well, this is what we use most in a api React them. He is used to update the status of our assembly. Then he takes two parameters, one is partialState, he is what we want to update the state, can be a target, may also be a method. In subsequent versions react more recommended method. The second is a callback. Then the callback is updated after the completion of the real state he will perform this callback. This approach can be seen inside invariant. This piece of code is invariant him a reminder. He partialState determine what is an object, method, or null. If you are not satisfied, there will be a string of follow-up reminder.
This is a trivial code. What is so important is it important that this.updater.enqueueSetState. That we call setState, in fact, call enqueueSetState. This is what we initialize Component enqueueSetState when passed in enqueueSetState this method. This is the way in which to achieve React dom, with the React is not related. Why do you want to do so, because of the different platforms, such as React dom and React native. The core they use exactly the same. That is, Component api is the same. But specific to update state. Update the design to render the state, then the rendering process is associated with the platform. react dom platform with him the way react native implementation platform is certainly not the same. So this part as a parameter passed to allow different platforms to come to a realization of his own customized way. That's why enqueueSetState to call in setState inside.
Next there is a prototype method is forceUpdate. The same with setState. Also called a method updater inside. Called the enqueueForceUpdate. This api is not very common, is forced to react to update it again, even if your state does not carry out an update.

 

/**
 * Deprecated APIs. These APIs used to exist on classic React classes but since
 * we would like to deprecate them, we're not going to move them over to this
 * modern base class. Instead, we define a getter that warns if it's accessed.
 */
if (__DEV__) {
  const deprecatedAPIs = {
    isMounted: [
      'isMounted',
      'Instead, make sure to clean up subscriptions and pending requests in ' +
        'componentWillUnmount to prevent memory leaks.',
    ],
    replaceState: [
      'replaceState',
      'Refactor your code to use setState instead (see ' +
        'https://github.com/facebook/react/issues/3236).',
    ],
  };
  const defineDeprecationWarning = function(methodName, info) {
    Object.defineProperty(Component.prototype, methodName, {
      get: function() {
        lowPriorityWarning(
          false,
          '%s(...) is deprecated in plain JavaScript React classes. %s',
          info[0],
          info[1],
        );
        return undefined;
      },
    });
  };
  for (const fnName in deprecatedAPIs) {
    if (deprecatedAPIs.hasOwnProperty(fnName)) {
      defineDeprecationWarning(fnName, deprecatedAPIs[fnName]);
    }
  }
}
Then see isMounted and replaceState. This is about to be abandoned two api. Both api itself because there is no how used, there is no particularly useful. The next version will not, so this will skip.

 

Here we can see the definition Component has ended. So the base class so that only a little thing, no other meaning, nor any related methods on the life cycle. See here must be very confused, this is no way of things, because we are beginning to see the source code when I was holding React.Component is very complex, he helped us to achieve a variety of logic. But in fact until the follow-up to see how React dom to create update and implement this whole process, I found this Component is only used to help us to carry some of the information.

 

Next we look at another base class, which is PureComponent

 

function ComponentDummy() {}
ComponentDummy.prototype = Component.prototype;

/**
 * Convenience component with default shallow equality check for sCU.
 */
function PureComponent(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  this.updater = updater || ReactNoopUpdateQueue;
}

const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
pureComponentPrototype.constructor = PureComponent;
// Avoid an extra prototype jump for these methods.
Object.assign(pureComponentPrototype, Component.prototype);
pureComponentPrototype.isPureReactComponent = true;

Then we can consider him PureComponent inheritance and Componnet. Two of them there is no inheritable things, because they received two things are exactly the same, all props, context, updater. Here with ComponentDummy to achieve a simple way similar to inheritance. PureComponent.prototype to a new ComponentDummy. ComponentDummy is an empty class. The Component prototypes assigned to the ComponentDummy prototype. Then turn ComponentDummy prototype assigned to the PureComponent. pureComponentPrototype constructor points to pureComponent. This is actually a succession of process implementation. In fact, that is exactly the same. The only difference is that the above plus a isPureReactComponent. He is identified as an inherited component from this class by such a property, he is a PureReactComponent. Then in the process of a subsequent update. React dom he will take the initiative to judge that he is not a PureComponent. The props then determines whether the update if this component needs to be updated.

 

Guess you like

Origin www.cnblogs.com/wzndkj/p/11913977.html