Open
Description
bindActionCreators.js
bindActionCreators在项目中比较少用到,属于那种不用也可以,用了会让代码更简洁的辅助函数。
这里贴一个官网的使用示例,比较好理解:
下面看一下bindActionCreators的源代码:
function bindActionCreator(actionCreator, dispatch) {
return function (this, ...args) {
return dispatch(actionCreator.apply(this, args))
}
}
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, but instead received: '${kindOf(
actionCreators
)}'. ` +
`Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?`
)
}
const boundActionCreators = {}
for (const key in actionCreators) {
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
bindActionCreators针对传入参数的不同有三种处理方法,下面分别来看看。
1. typeof actionCreators === 'function'
当传入的actionCreators为一个函数时,即只传入了一个actionCreator,就会调用bindActionCreator来处理。
function bindActionCreator(actionCreator, dispatch) {
return function() {
return dispatch(actionCreator.apply(this, arguments))
}
}
// 调用bindActionCreators,传入参数
// 注意这里的actionCreators是一个函数,不是一个对象
bindActionCreators(actionCreators, dispatch)
===> 最终处理结果
// 最后在子组件里得到的函数如下所示,可以直接调用
// 组件内不用再感知redux,不用再引入actionCreator,直接传参调用即可派发action
function (this, ...args) {
return dispatch(actionCreator.apply(this, args))
}
2. 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"?`
)
提示开发者actionCreators类型错误,应该是一个非空对象或者是函数。
3. 默认情况,即actionCreators是一个对象,里面包含多个actionCreator函数
const boundActionCreators = {}
for (const key in actionCreators) {
const actionCreator = actionCreators[key]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
和情况一类似,对actionCreators中的每一项都执行情况一的操作,最后将所有包装好的函数放在一个对象中返回。