歡迎關注redux源碼分析系列文章:
redux源碼分析之一:createStore.js
redux源碼分析之二:combineReducers.js
redux源碼分析之三:bindActionCreators.js
redux源碼分析之四:compose.js
redux源碼分析之五:applyMiddlewaregit
bindActionCreators.js文件算是很是簡單的一個文件了,該文件就實現一個目的:之前這樣觸發一個action,即dispatch(actionCreator(args)),如今變成這樣觸發一個action: boundActionCreator(args)。目的很單純,簡化某個action的調用。github
實現上面那個效果,僅需一行代碼,也就是源碼文件中的第一個函數:redux
function bindActionCreator(actionCreator, dispatch) { return (...args) => dispatch(actionCreator(...args)) }
可是bindActionCreators.js文件對外提供的並非上面的函數,而是另一個,源碼以下:segmentfault
export default function bindActionCreators(actionCreators, dispatch) { //若是actionCreators是一個函數,則說明只有一個actionCreator,那直接調用bindActionCreator就好了 if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch) } //若是是actionCreator是對象,或者是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"?` ) } //保持actionCreators裏面原來的key,只是把key對應的value都轉成了boundActionCreator const keys = Object.keys(actionCreators) const boundActionCreators = {} for (let i = 0; i < keys.length; i++) { const key = keys[i] const actionCreator = actionCreators[key] //只對value是函數的key進行轉換,其餘的都過濾掉了 if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch) } } //返回綁定以後的對象 return boundActionCreators }
這個函數作的事情也很簡單,只是把actionCreators這個對象裏面包含的每個actionCreator按照原來的key的方式所有都封裝了一遍而已,具體看代碼嘍app
完整解析請參考個人github:https://github.com/abczhijia/...,若是對您有幫助,歡迎star,有任何問題也請指正。函數