Source Time
function bindActionCreator(actionCreator, dispatch) {
return function() {
return dispatch(actionCreator.apply(this, arguments))
}
}
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, 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]
if (typeof actionCreator === 'function') {
boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
}
}
return boundActionCreators
}
Analysis
我們知道牡属,在redux中,action
是一個plain object谎替,所以為了方便生成這個action
偷溺,我們引入了action creator
的概念,其實就是一個函數(shù)院喜,接受一個參數(shù)亡蓉,返回一個對象,比如下面的addTodo
:
const addTodo = (text) => {
return {
text,
finished: false,
};
};
每當我們想添加一個todo的時候只需要調用addTodo
并傳入名字就行了喷舀,但是redux的運行不僅僅止步于此砍濒,更關鍵的是將產生的這個action
給觸發(fā),也就是dispatch
硫麻,所以爸邢,bindActionCreators
就是更進一步,不僅僅是產生action
拿愧,還實現(xiàn)自動dispatch
杠河。
核心部分是最開始的五行——函數(shù)bindActionCreator
:
function bindActionCreator(actionCreator, dispatch) {
return function() {
return dispatch(actionCreator.apply(this, arguments))
}
}
創(chuàng)建一個函數(shù),名字叫作bindActionCreator
浇辜,接受兩個參數(shù)券敌,一個是actionCreator
,也就是提到的addTodo
柳洋,第二個參數(shù)是dispatch
待诅,這里的就是store提供的api。而bindActionCreators
其實是將接受范圍擴大化熊镣,不僅僅允許actionCreators是函數(shù)卑雁,也可以是一個對象,這里不過多贅述绪囱。
實際使用往往像是這樣的:
const addTodoBindDispatch = bindActionCreators(addTodo, store.dispatch);
PS. 多說一句测蹲,感覺這個api并沒有什么卵用
All
index
compose
applyMiddleware
bindActionCreators
combineReducers
createStore