redux的核心就在于createStore 和 applyMiddleware这两个类里面
bindActionCreator这个只是一个辅助类
下面我们看看源码
function bindActionCreator(actionCreator, dispatch) {
return (...args) => dispatch(actionCreator(...args)) // 返回函数 dispatch actionCreator这个函数
}
export default function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') { actionCreators 如果是一个函数 调用上面的方法
return bindActionCreator(actionCreators, dispatch)
}
if (typeof actionCreators !== 'object' || actionCreators === null) { // actionCreators 只接受对象或函数,函数已经在上面进行了判断。
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) // 获取actionCreators对象的key
const boundActionCreators = {}
for (let i = 0; i < keys.length; i++) { // 循环遍历key
const key = keys[i]
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') { // 如果key对应函数 调用上面的方法
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators // 返回绑定了dispath的对象
}
通过上面的代码可以看到 核心的代码就是
function bindActionCreator(actionCreator, dispatch) {
return (...args) => dispatch(actionCreator(...args))
}
这个方法,通过这个方法将actionCreator函数与dispatch进行了绑定。
由于我是一般都是react-redux和redux一起用,所以对对于bindActionCreators这个API用的比较少,可能理解也不够深入。