redux源码分析

这篇文章会很长。redux源码读起来并不困难。读懂redux的源码有利于更好的使用redux。
但是react-redux复杂多。所以分阶段写。

redux源码分析

在使用redux中,比较重要的三个函数: createStore,store.dispatch,reducer。其中有一个比较难以理解的点是,为什么reducer每次都要返回一个新的变量。我们先来分析 createStore函数。
redux整个设计遵循的是订阅-更新模式。

export default function createStore(reducer, preloadedState, enhancer) {
  let currentReducer = reducer
  let currentState = preloadedState
  let currentListeners = []
  let nextListeners = currentListeners
  let isDispatching = false


  function getState() {
    if (isDispatching) {
      throw new Error(
        'You may not call store.getState() while the reducer is executing. ' +
          'The reducer has already received the state as an argument. ' +
          'Pass it down from the top reducer instead of reading it from the store.'
      )
    }

    return currentState
  }
}

其中,currentState是维持在createStore的中的变量。也是存储整个工程的state数据的变量。

  • dispatch函数
  function dispatch(action) {
   ...

    if (isDispatching) {
      throw new Error('Reducers may not dispatch actions.')
    }

    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
  }

dispatch函数可以看到reducer的设计思想。currentReducer是我们调用createStore时传递进来的reducer函数。一般reducer函数是这样定义的:

const reducers = (state = initialState, action) => {
    let newState = Object.assign({}, state);
    switch (action.type) {
        case types.GET_ORDERS:
            newState.orderInfo = action.response;

        case types.GET_GOODS:
            newState.goodsInfo = action.response;

        case types.SET_ALL_EXPRESS_COMPANY:
            newState.expressCompany = action.response;

        case types.SET_EXPRESS_COMPANY:
            newState.expressInfo =  {
                trackingNumber: state.expressInfo.trackingNumber,
                shippingId: action.response.shippingId,
                shippingName: action.response.shippingName,
            }
        case types.SET_EXPRESS_STATUS:
            newState.showExpressSuccessModal = action.response;

        case types.INIT_TRACK_NUMBER:
            newState.expressInfo = {
                trackingNumber: action.response,
                shippingId: state.expressInfo.shippingId,
                shippingName:  state.expressInfo.shippingName,
            }
    }

   return newState
}
export default reducers

而action的数据格式一般是这样的:

{
        type: types.SEND_GOODS,
        response: response
    }

连在一起看语句currentState = currentReducer(currentState, action) 是不是好懂很多呢?将保存在store上的state传入reducer函数中,获得新的state(要复制一份state的原因还不清楚)
接下来

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

那么currentListeners何时更新?我们接着看一下subscribe函数。

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

    if (isDispatching) {
      throw new Error(
        'You may not call store.subscribe() while the reducer is executing. ' +
          'If you would like to be notified after the store has been updated, subscribe from a ' +
          'component and invoke store.getState() in the callback to access the latest state. ' +
          'See https://redux.js.org/api-reference/store#subscribe(listener) for more details.'
      )
    }

    let isSubscribed = true

    ensureCanMutateNextListeners()
    nextListeners.push(listener)

    return function unsubscribe() {
      if (!isSubscribed) {
        return
      }
      ....

      isSubscribed = false

      ensureCanMutateNextListeners()
      const index = nextListeners.indexOf(listener)
      nextListeners.splice(index, 1)
    }
  }

执行subscribe函数,实际上就是将回调函数加入nextListeners这个list中,当执行dispatch时,nextListeners中每个listener函数会顺序执行。这样就完成了每次store中数据发生变更,subscribe中函数就会执行一次。至于为什么会有两个变量currentListenersnextListeners来维持回调队列,还不是很清楚原因。

最后提出三个问题:

  • 为什么reduce函数中中要返回新的state
  • 为什么listener也要保持纯净
  • 为什么react中这么喜欢使用mutual哲学

后续更新:

  • observable 由于没有用过observable,这部分的源码先不看。

react-redux源码分析

  • 如何感知store的变化
  • 如何修改state的变化

redux-thunk源码分析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 使用redux+react已有一段时间,刚开始使用并未深入了解其源码,最近静下心细读源码,感触颇深~ 本文主要包含...
    字节跳动技术团队阅读 5,484评论 0 5
  • Redux是React核心开发人员的开发的一个JavaScript 状态容器,提供可预测化的状态管理。 Redux...
    人失格阅读 4,304评论 0 0
  • 1 redux使用步骤 React仅仅是一个前端View框架库,可以看做是MVC里面的V。没有解决组件间通信,MV...
    Dabao123阅读 3,106评论 0 2
  • 学习必备要点: 首先弄明白,Redux在使用React开发应用时,起到什么作用——状态集中管理 弄清楚Redux是...
    贺贺v5阅读 12,887评论 10 58
  • 咪蒙的公众号被关了,我都不知道,只是当网上出现了许多评论文章一炮而红时,我才注意到最新一篇的文章看不到,而之所以不...
    似水若烟阅读 4,042评论 20 8