redux createStore 源码学习

createStore在redux类库中是篇幅最长的一个函数。它主要的作用是构建redux的store。

当createStore函数遇到enhance参数

function createStore(reducer, preloadedState, enhancer)

if (typeof enhancer !== 'undefined') {
    if (typeof enhancer !== 'function') {
      throw new Error('Expected the enhancer to be a function.')
    }

    return enhancer(createStore)(reducer, preloadedState)
  }


在createStore函数中,只要enhancer存在,创建store的过程将会在enhancer函数中完成。这保证了可以在enhancer函数中装饰和包装dispatch核心方法。有兴趣可看:applyMiddleware源码分析

dispatch函数:


 function dispatch(action) {
    if (!isPlainObject(action)) {
      throw new Error(
        'Actions must be plain objects. ' +
        'Use custom middleware for async actions.'
      )
    }

    if (typeof action.type === 'undefined') {
      throw new Error(
        'Actions may not have an undefined "type" property. ' +
        'Have you misspelled a constant?'
      )
    }

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }
    //这就是为什么reducer函数处理返回数据出现错误也不报错的原因。
    //直接在dispatch函数内进行错误处理,reducer处理action的错误并不会报给开发者。
    //(真坑爹,这导致开发者很难进行错误追踪。)
    try {
      isDispatching = true
      currentState = currentReducer(currentState, action)
    } finally {
      isDispatching = false
    }

    const listeners = currentListeners = nextListeners
    for (let i = 0; i < listeners.length; i++) {
      const listener = listeners[i]
      listener()
    }

    return action
  }

初始化store的state


  // When a store is created, an "INIT" action is dispatched so that every
  // reducer returns their initial state. This effectively populates
  // the initial state tree.
  dispatch({ type: ActionTypes.INIT })

源代码中的英文注释,已经说明了这一行代码的作用。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 前言 本文 有配套视频,可以酌情观看。 文中内容因各人理解不同,可能会有所偏差,欢迎朋友们联系我讨论。 文中所有内...
    珍此良辰阅读 12,208评论 23 111
  • 一、什么情况需要redux? 1、用户的使用方式复杂 2、不同身份的用户有不同的使用方式(比如普通用户和管...
    初晨的笔记阅读 2,136评论 0 11
  • http://gaearon.github.io/redux/index.html ,文档在 http://rac...
    jacobbubu阅读 80,431评论 35 198
  • 上周六参加了一个公司的面试,因为是很长时间以来的第一次面试,发挥的并不是很好,有两个下来一想就明白的问题在当时却卡...
    夏尔先生阅读 6,489评论 0 15
  • 在学习了redux过程中,了解到中间件这个名词,但是我看了十遍,也完全就是懵逼的状态。于是又重复敲了几次代码也不能...
    绰号陆拾柒阅读 600评论 0 0

友情链接更多精彩内容