Redux源碼(四) —— bindActionCreators.js

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的概念,其實就是一個函數,接受一個參數,返回一個對象,好比下面的addTodojavascript

const addTodo = (text) => {
  return {
    text,
    finished: false,
  };
};
複製代碼

每當咱們想添加一個todo的時候只須要調用addTodo並傳入名字就好了,可是redux的運行不單單止步於此,更關鍵的是將產生的這個action給觸發,也就是dispatch,因此,bindActionCreators就是更進一步,不單單是產生action,還實現自動dispatchjava

核心部分是最開始的五行——函數bindActionCreatorredux

function bindActionCreator(actionCreator, dispatch) {
  return function() {
    return dispatch(actionCreator.apply(this, arguments))
  }
}
複製代碼

建立一個函數,名字叫做bindActionCreator,接受兩個參數,一個是actionCreator,也就是提到的addTodo,第二個參數是dispatch,這裏的就是store提供的api。而bindActionCreators實際上是將接受範圍擴大化,不單單容許actionCreators是函數,也能夠是一個對象,這裏不過多贅述。api

實際使用每每像是這樣的:app

const addTodoBindDispatch = bindActionCreators(addTodo, store.dispatch);
複製代碼

PS. 多說一句,感受這個api並無什麼卵用函數

All

相關文章
相關標籤/搜索