let currentReducer = reducer let currentState = preloadedState let currentListeners = [] let nextListeners = currentListeners let isDispatching = false
let currentReducer = reducer // 传进来的reducer let currentState = preloadedState // 传进来的初始状态 let currentListeners = [] // 观察者函数回调函数的集合 let nextListeners = currentListeners // currentListeners的浅拷贝 let isDispatching = false// 是否正在处理Action
那我们就一个一个看
getState
这个函数最为的简单,函数返回当前的状态对象。 完整的代码如下
1 2 3 4 5 6 7 8 9 10 11
functiongetState() { if (isDispatching) { thrownewError( '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.', ) }
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#subscribelistener 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#subscribelistener for more details.', ) }
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.') }
let proto = obj while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto) }
returnObject.getPrototypeOf(obj) === proto }
先用简单的typeof操作符来判断,顺便把null的情况也给排除出去。
接下来就是要排除那些自定义的构造函数所产生的对象。
Object.getPrototypeOf获取一个对象的原型。
通过while循环不断遍历原型链,直到最顶端的原型。
排除的依据就是如果原型链上出现了除了Object.prototype之外的原型,就返回false。
1 2 3 4 5
if (typeof action.type === 'undefined') { thrownewError( 'Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?', ) }
接下来判断了action的type属性,他不能是undefined。
1 2 3
if (isDispatching) { thrownewError('Reducers may not dispatch actions.') }
// 防止传入多个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.', ) }
// enhancer必须是一个函数 if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { thrownewError('Expected the enhancer to be a function.') }