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

相关文章
相关标签/搜索