bindActionCreators
是redux
提供的一個輔助方法,可以讓咱們以方法的形式來調用action
。同時,自動dispatch
對應的action
。這個模塊的代碼十分簡單,只要你們明白了Function.prototype.apply
的使用,就可以很清晰的理解這個模塊中的每一行代碼。由於,這個模塊設計到的內容有點少,因此咱們就直接分析源碼。git
function bindActionCreator(actionCreator, dispatch) { // 這個函數的主要做用就是返回一個函數,當咱們調用返回的這個函數的時候,就會自動的dispatch對應的action // 這一塊其實能夠更改爲以下這種形式更好 // return function(...args) {return dispatch(actionCreator.apply(this, args))} return function() { return dispatch(actionCreator.apply(this, arguments)) } }
/** 參數說明: actionCreators: action create函數,能夠是一個單函數,也能夠是一個對象,這個對象的全部元素都是action create函數 dispatch: store.dispatch方法 */ export default function bindActionCreators(actionCreators, dispatch) { // 若是actionCreators是一個函數的話,就調用bindActionCreator方法對action create函數和dispatch進行綁定 if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch) } // actionCreators必須是函數或者對象中的一種,且不能是null 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 create函數的名字 const keys = Object.keys(actionCreators) // 保存dispatch和action create函數進行綁定以後的集合 const boundActionCreators = {} for (let i = 0; i < keys.length; i++) { const key = keys[i] const actionCreator = actionCreators[key] // 排除值不是函數的action create if (typeof actionCreator === 'function') { // 進行綁定 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } } // 返回綁定以後的對象 /** boundActionCreators的基本形式就是 { actionCreator: function() {dispatch(actionCreator.apply(this, arguments))} } */ return boundActionCreators }
這就是對bindActionCreators
源碼的一個總體解讀,水平有限,歡迎拍磚。後續的源碼解讀和測試例子能夠關注:redux源碼解讀倉庫github