Redux源码阅读_1(下)

subscribe(listener)

添加一个变化监听器,每当 dispatch action 的时候就会执行。

该方法主要有如下操作:
1、将listener推入listeners队列,等待dispatch action时调用。
2、修改isSubscribe的值。
3、返回unsubscribe函数。(函数内操作:1、修改isSubscribe值;1、listeners队列删除listener)

代码如下:

function subscribe(listener: () => void) {
    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/store#subscribelistener for more details.'
      )
    }

    let isSubscribed = true

    ensureCanMutateNextListeners()
    nextListeners.push(listener)

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

      if (isDispatching) {
        throw new Error(
          'You may not unsubscribe from a store listener while the reducer is executing. ' +
            'See https://redux.js.org/api/store#subscribelistener for more details.'
        )
      }

      isSubscribed = false

      ensureCanMutateNextListeners()
      const index = nextListeners.indexOf(listener)
      nextListeners.splice(index, 1)
      currentListeners = null
    }
  }
replateReducer(nextReducer)

这个方法没怎么用到过,代码写法也有地方没看懂。。。

主要操作:
1、将当前reducer替换为nextReducer。
2、dispatch一个replace action。(dispatch的操作就是上面那个函数里的,修改属性状态啦,执行所有listener啦,返回action啦)
3、返回store。

代码如下:

  function replaceReducer(
    nextReducer: Reducer
  ): Store, NewActions, StateExt, Ext> & Ext {
    if (typeof nextReducer !== 'function') {
      throw new Error('Expected the nextReducer to be a function.')
    }

    ;((currentReducer as unknown) as Reducer<
      NewState,
      NewActions
    >) = nextReducer

    dispatch({ type: ActionTypes.REPLACE } as A)
    // change the type of the store by casting it to the new store
    return (store as unknown) as Store<
      ExtendState,
      NewActions,
      StateExt,
      Ext
    > &
      Ext
  }

createStore文件的主要内容就是这些,还有其他一些类型检测以及工具函数的代码未放上来,这个源码里都有。

你可能感兴趣的:(Redux源码阅读_1(下))