上代码先
export default function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch) } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error( bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}.
+
Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?) } var keys = Object.keys(actionCreators) var boundActionCreators = {} for (var i = 0; i < keys.length; i++) { var key = keys[i] var actionCreator = actionCreators[key] if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } } return boundActionCreators }
export 出来的bindActionCreators 主函数
首先判断进来的是不是一个function,如果传进来的只是一个函数,那么调用bindActionCreator 这个方法。
如果不是object 也不是 function ,那么抛出异常
如果是一个object,那么生成一个boundActionCreators对象,对传入object 的属性遍历,对每一个属性中的方法执行bindActionCreator,然后把生成的新方法,用同名key赋值给boundActionCreators 对象,这样boundActionCreators对象就有了跟传入对象同名的属性。
最后我们来看看bindActionCreator做了什么
function bindActionCreator(actionCreator, dispatch) { return (...args) => dispatch(actionCreator(...args)) }
这个函数返回一个匿名函数,匿名函数中传入的所有参数,传递给actionCreator,然后dispatch。其实就是把传入的actionCreator绑定一个dispatch,这样actionCreator 中就可以使用dispatch来分发action了。
我们再来看一下dispatch 是怎么写的
function dispatch(action) { if (!isPlainObject(action)) { throw new Error( 'Actions must be plain objects. ' + 'Use custom middleware for async actions.' ) } if (typeof action.type === 'undefined') { throw new Error( 'Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?' ) } if (isDispatching) { throw new Error('Reducers may not dispatch actions.') } try { isDispatching = true currentState = currentReducer(currentState, action) } finally { isDispatching = false } var listeners = currentListeners = nextListeners for (var i = 0; i < listeners.length; i++) { var listener = listeners[i] listener() } return action }
网友评论