react 源码之setState

更新日期: 2019-02-26 阅读: 2.9k 标签: react

1:monorepo (react代码管理方式)

与multirepo 相对。 monorepo是单代码仓库, 是把所有相关项目都集中在一个代码仓库中,每个module独立发布,每个module都有自己的依赖项(package.json),能够作为独立的npm package发布,只是源码放在一起维护。

下图是典型monorepo目录图,react为例



2: setState

 setState  "react/src/ReactBaseClasses.js"

* @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');
};


可以看到,干了两件事情:第一:调用方法invariant(), 第二:调用 this.updater.enqueueSetState

 invariant() "shared/invariant"  让我们先去看看第一个方法干嘛了!

export default function invariant(condition, format, a, b, c, d, e, f) {
  validateFormat(format);

  if (!condition) { // 导出了一个方法,可以看出如果condition为false的话, 抛出错误
    let error;
    if (format === undefined) {
      error = new Error(
        'Minified exception occurred; use the non-minified dev environment ' +
          'for the full error message and additional helpful warnings.',
      );
    } else {
      const args = [a, b, c, d, e, f];
      let argIndex = 0;
      error = new Error(
        format.replace(/%s/g, function() {
          return args[argIndex++];
        }),
      );
      error.name = 'Invariant Violation';
    }

    error.framesToPop = 1; // we don't care about invariant's own frame
    throw error;
  }
}


得出,这个方法就是判断partialState 的type, 不正确的话抛错误。 Facebook工程师把这个抛错误封装了成了invariant函数,嗯,以后工作中可以这样做!

his.updater.enqueueSetState  让我们再去看看第二个是干嘛了!

首先,this.updater 什么鬼:

import ReactNoopUpdateQueue from './ReactNoopUpdateQueue';
/**
 * Base class helpers for the updating state of a component.
 */
function Component(props, context, updater) {//在这个文件中导出了两个构造函数Component和PureComponent
  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; // 这里是this.updater, 这个标黄的 是default updater
}


ReactNoopUpdateQueue  "react/src/ReactNoopUpdateQueue.js" 导出的一个对象,里面有好几个方法,其中一个就是setState用到的this.updater.enqueueSetState(this, partialState, callback, 'setState'):

enqueueSetState: function(
    publicInstance, // 实例this
    partialState, // 新的state
    callback, // 回调   
    callerName,
  ) {
    warnNoop(publicInstance, 'setState');
  },
// 啊 这个里面是default updater


enqueueSetState定义 "react-dom/src/server/ReactPartialRenderer.js"    实际的updater从哪里来的呢?哎,我是暂时没找到,但是,我知道这个实际的updater肯定有enqueueSetState方法,那我就全局搜索一下,找到enqueueSetState的定义:

let updater = {  //这里是updater对象,里面各种方法
      isMounted: function(publicInstance) {
        return false;
      },
      enqueueForceUpdate: function(publicInstance) {
        if (queue === null) {
          warnNoop(publicInstance, 'forceUpdate');
          return null;
        }
      },
      enqueueReplaceState: function(publicInstance, completeState) {
        replace = true;
        queue = [completeState];
      },
      enqueueSetState: function(publicInstance, currentPartialState) {
        if (queue === null) { // 这是一个错误情况,下面代码中warnNoop()方法就是在dev环境中给出空操作警告的
          warnNoop(publicInstance, 'setState');
          return null;
        }
        queue.push(currentPartialState); // 把现在要更新的state  push到了一个queue中
      },
    };
     // 接下来代码解决了我上面找不到实际updater的疑问!
    let inst;
    if (shouldConstruct(Component)) {
      inst = new Component(element.props, publicContext, updater); // 在new的时候,就把上面真实的updater传进去啦!!!
.......后面还有好多,不过与我这一期无关了.


queue 这是react提升性能的关键。并不是每次调用setState react都立马去更新了,而是每次调用setState, react只是push到了待更新的queue中! 下面是对这个queue的处理!

if (queue.length) {
        let oldQueue = queue;
        let oldReplace = replace;
        queue = null;
        replace = false;

        if (oldReplace && oldQueue.length === 1) { // 队列里面,只有一个,直接更换。
          inst.state = oldQueue[0];
        } else {  // 队列里面有好几个,先进行合并,再更新
          let nextState = oldReplace ? oldQueue[0] : inst.state;
          let dontMutate = true;
          for (let i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
            let partial = oldQueue[i];
            let partialState =
              typeof partial === 'function'
                ? partial.call(inst, nextState, element.props, publicContext)
                : partial;
            if (partialState != null) {  // 这里合并啦,新的是nextState
              if (dontMutate) {
                dontMutate = false;
                nextState = Object.assign({}, nextState, partialState);
              } else {
                Object.assign(nextState, partialState);
              }
            }
          }   
          inst.state = nextState;  //最后赋值给实例
        }
      } else {
        queue = null;
      }


 原文来自:https://www.cnblogs.com/yadiblogs/archive/2019/02/27/10446748.html


本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://fly63.com/article/detial/2143

相关推荐

Gatsby.js_一款基于React.js静态站点生成工具

Gatsby能快速的使用 React 生态系统来生成静态网站,可以结合React Component、Markdown 和服务端渲染来完成静态网站生成让他更强大。

解决vscode 开发react 导入绝对路径 无法跳转的问题

相对路径可正常跳转,但是在webpack配置alias使用绝对路径后无法跳转.解决办法:需要添加一个jsconfig文件,如下:

react router中页面传值的三种方法

这篇文章主要介绍React Router定义路由之后如何传值,有关React和React Router 。react router中页面传值的三种方法:props.params、query、state

React常用hook的优化useEffect浅比较

先说说react原版的useEffect使用起来不便的地方,这里的effect每次更新都会执行,因为第三个参数一直是不等的,第二是在deps依赖很多的时候是真的麻烦

React 监听页面滚动,界面动态显示

当页面滚动时,如何动态切换布局/样式, 添加滚动事件的监听/注销

React + Webpack 构建打包优化

React 相关的优化:使用 babel-react-optimize 对 React 代码进行优化,检查没有使用的库,去除 import 引用,按需打包所用的类库,比如 lodash 、echarts 等.Webpack 构建打包存在的问题两个方面:构建速度慢,打包后的文件体积过大

react-router v4 按需加载的配置方法

在react项目开发中,当访问默认页面时会一次性请求所有的js资源,这会大大影响页面的加载速度和用户体验。所以添加按需加载功能是必要的,以下是配置按需加载的方法

React事件处理函数必须使用bind(this)的原因

学习React的过程中发现调用函数的时候必须使用bind(this),之后直接在class中声明函数即可正常使用,但是为什么呢,博主进行了一番查阅,总结如下。

grpc-web与react的集成

使用create-react-app脚手架生成react相关部分,脚手架内部会通过node自动起一个客户端,然后和普通的ajax请求一样,和远端服务器进行通信,只不过这里采用支持rpc通信的grpc-web来发起请求,远端采用docker容器的node服务器,node服务器端使用envoy作为代理

react中的refs属性的使用方法

React 支持一种非常特殊的属性 Ref ,你可以用来绑定到 render() 输出的任何组件上。这个特殊的属性允许你引用 render() 返回的相应的支撑实例( backing instance )。这样就可以确保在任何时间总是拿到正确的实例

点击更多...

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!