exportdefaultfunctioncreateStore(reducer, preloadedState, enhancer) { if ( (typeof preloadedState === 'function' && typeof enhancer === 'function') || (typeof enhancer === 'function' && typeofarguments[3] === 'function') ) { thrownewError( '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 reducer !== 'function') { thrownewError('Expected the reducer to be a function.') }
let currentReducer = reducer let currentState = preloadedState let currentListeners = [] let nextListeners = currentListeners let isDispatching = false
... }
先忽略过多的代码,首先看看最后的处理:
1 2 3 4 5
let currentReducer = reducer; let currentState = preloadedState; let currentListeners = []; let nextListeners = currentListeners; let isDispatching = false;
functionsubscribe(listener) { if (typeof listener !== "function") { thrownewError("Expected the listener to be a function."); }
if (isDispatching) { thrownewError( "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." ); }
returnfunctionunsubscribe() { if (!isSubscribed) { return; }
if (isDispatching) { thrownewError( "You may not unsubscribe from a store listener while the reducer is executing. " + "See https://redux.js.org/api-reference/store#subscribe(listener) for more details." ); }
isSubscribed = false;
ensureCanMutateNextListeners(); const index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; }
functiondispatch(action) { if (!isPlainObject(action)) { thrownewError( "Actions must be plain objects. " + "Use custom middleware for async actions." ); }
if (typeof action.type === "undefined") { thrownewError( 'Actions may not have an undefined "type" property. ' + "Have you misspelled a constant?" ); }
if (isDispatching) { thrownewError("Reducers may not dispatch actions."); }
exportdefaultfunctionapplyMiddleware(...middlewares) { returncreateStore =>(...args) => { const store = createStore(...args); let dispatch = () => { thrownewError( "Dispatching while constructing your middleware is not allowed. " + "Other middleware would not be applied to this dispatch." ); };