首先看一下函数的使用场景:
@connect(
state => {
const { } = state;
return { }
},
dispatch => ({
actions: bindActionCreators({ ...actions, ...otheractions }, dispatch)
})
)
没错,就是配合connect使用的函数。他接收actions的集合和一个dispatch作为参数,效果说白了就是用dispatch给action包起来了。
function bindActionCreator(actionCreator, dispatch) {
return (...args) => dispatch(actionCreator(...args))
}
export default function bindActionCreators(actionCreators, dispatch) {
if (typeof actionCreators === 'function') { //官方解释为:你可以只传入一个函数为参数,他会给这个函数的返回结果添加diapatch处理。
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] //根据传入参数的key获得value,actionCreator,顾名思义,返回action的函数。
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
} //
}
return boundActionCreators //为其添加dispatch并返回。
}
由上述代码可知:我传入的...actions,应该为 xxx:createAction("XXXXXX")
或者 xxx = createAction("XXXXXX"),这个时候只要传一个xxx就可以了。