function bindActionCreator(actionCreator, dispatch) {
//其实,bindActionCreators的核心代码就是在这里,让每一个action函数最外层都被store.dispatch包含。
//这样就可以保障action函数在任何地方都可以被调用。
return (...args) => dispatch(actionCreator(...args))
}
//在这里处理actionCreators中的每一个函数,将每一个函数的最外层都包一层store.dispatch
//一调用action函数实际调用的是store.dispatch(action())进行处理。
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"?`
)
}
const keys = Object.keys(actionCreators)
const boundActionCreators = {}
for (let i = 0; i < keys.length; i++) {
const key = keys[i]
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
网友评论