redux中间件源码分析

废话不多说,直接上干货:

首先说下middleware怎么用
 store = createStore(reducer, applyMiddleware(middleware, middleware2));

下面先来看createStore里面干了什么,直接上源码

export default function createStore(reducer, preloadedState, enhancer) {

  if (

    (typeof preloadedState === 'function' && typeof enhancer === 'function') ||

    (typeof enhancer === 'function' && typeof arguments[3] === 'function')

  ) {

    throw new Error(

      'It looks like you are passing several store enhancers to ' +

        'createStore(). This is not supported. Instead, compose them ' +

        'together to a single function.'

    )

  }

  if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {

    enhancer = preloadedState

    preloadedState = undefined

  }

  if (typeof enhancer !== 'undefined') {

    if (typeof enhancer !== 'function') {

      throw new Error('Expected the enhancer to be a function.')

    }

    return enhancer(createStore)(reducer, preloadedState)

  }

  if (typeof reducer !== 'function') {

    throw new Error('Expected the reducer to be a function.')

  }

  let currentReducer = reducer

  let currentState = preloadedState

  let currentListeners = []

  let nextListeners = currentListeners

  let isDispatching = false

  return {

    dispatch,

    subscribe,

    getState,

    replaceReducer,

    [$$observable]: observable

  }

}

你可能感兴趣的:(redux中间件源码分析)