廢話不多說,直接上干貨:
首先說下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
? }
}