zoukankan      html  css  js  c++  java
  • 【React源码解读】react-component

    源码在线地址:https://github.com/facebook/react/blob/master/packages/react/src/ReactBaseClasses.js

    // BaseReactClasses.js
    
    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;
    }
    
    /**
    props:,
    context,
    refs: 挂载节点在上面
    updater: 我们可能并没有在react component使用到过,承载了实际的component更新操作
    */
    
    
    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');
    };
    
    /**
    partialState: 一个状态,可以是一个对象or方法(后续更加推荐使用一个方法)
    callback: 回调
    
    invariant(...): 判断下是不是一个对象or方法,然后提示
    
    this.updater.enqueueSetState(this, partialState, callback, 'setState');
    具体实现方法在react-dom中,具体学习会在react-dom中学习
    
    为什么updater要作为参数传入进来?
    不同的平台,比如react-dom,react-native,用到的核心例如COmponet是一样的,但是具体的涉及到更新state要走的流程,更新state后要渲染及渲染的流程是跟平台有关的,作为参数可以让不同的平台传入进来,定制
    };
    */
    
    Component.prototype.forceUpdate = function(callback) {
      this.updater.enqueueForceUpdate(this, callback, 'forceUpdate');
    };
    
    /**
    不常用,和setState类似,其实就是强制Component更新一遍,哪怕状态没有更新
    */
    
    
    function ComponentDummy() {}
    ComponentDummy.prototype = Component.prototype;
    
    
    function PureComponent(props, context, updater) {
      this.props = props;
      this.context = context;
      
      this.refs = emptyObject;
      this.updater = updater || ReactNoopUpdateQueue;
    }
    
    const pureComponentPrototype = (PureComponent.prototype = new ComponentDummy());
    pureComponentPrototype.constructor = PureComponent;
    
    Object.assign(pureComponentPrototype, Component.prototype);
    pureComponentPrototype.isPureReactComponent = true;
    
    /**
    其实可以认为为继承于Component,使用ComponetDummy实现了一个简单的继承方式
    
    惟一的区别就是在pureComponetPrototype上添加了一个isPureReactComponet属性,使得在后续更新中,react-dom会去主动判断是否是个pure component,决定是否更新
    */
    
  • 相关阅读:
    hdu 4577 X-Boxes 大数
    hdu 4576 Robot 概率DP
    将IP地址转化为整数
    MyISAM压缩表
    yii2 模态框
    MySQL数据库设计
    foreach循环赋值问题
    实用的网站
    判断链接地址是否有效
    tp5获取配置文件信息
  • 原文地址:https://www.cnblogs.com/fe-linjin/p/11708952.html
Copyright © 2011-2022 走看看