redux——boundActionCreators原理

it2023-03-01  98

一、boundActionCreators

boundActionCreators接收两个参数:

1.actionCreators:可以是一个包含action创建函数的对象或者一个action函数,如果是一个action创建函数直接返回一个自动分发的action创建函数 2.dispatch:仓库的dispatch函数

二、源码:

// 通过这个函数返回一个自动分发的action创建函数 function bindActionCreator(actionCreator, dispatch) { return function() { return dispatch(actionCreator.apply(this, arguments)) } } export default function bindActionCreators(actionCreators, dispatch) { // 判断传入的actionCreators是不是一个函数 如果是一个函数 说明传入的是一个action创建函数 // 直接返回一个dispatch分发函数 if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch) } // actionCreators如果不是一个函数也不是一个对象或者为空直接报错 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"?` ) } // 用来保存所有的action的对象 const boundActionCreators = {} // 遍历传入的actionCreators对象 如果对象的属性值是一个函数调用bindActionCreator添加到boundActionCreators对象中 for (const key in actionCreators) { const actionCreator = actionCreators[key] // 判断对象中的每个action创建函数是不是一个函数 if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } } // 最后返回整合后的boundActionCreators对象 return boundActionCreators }
最新回复(0)