根据Redux文档学源码(三)

123 阅读1分钟

最近工作比较忙,学习的时间比较少,所以这篇文章更新的有点晚 今天我们主要来看看Redux中的一个工具函数,bindActionCreators首先我们来看看源码是什么样子的

export default function bindActionCreators(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {
    return bindActionCreator(actionCreators, dispatch);
  }

  if (typeof actionCreators !== 'object' || actionCreators === null || actionCreators === undefined) {  // eslint-disable-line no-eq-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"?`
    );
  }

  return mapValues(actionCreators, actionCreator =>
    bindActionCreator(actionCreator, dispatch)
  );
}

首先这个函数接受两个参数,一个是我们的action构造器,他可以是一个函数也可以是一个,值为action构造器的对象,第二个参数是一个dispatch函数,函数内部的实现逻辑很简单,首先对actionCreators进行判断是不是函数,如果是的话直接返回bindActionCreator(actionCreators, dispatch)。也就是下面这个函数

function bindActionCreator(actionCreator, dispatch) {
  return (...args) => dispatch(actionCreator(...args));
}

这个函数的主要作用是返回一个能接受参数的箭头函数,注意此处的箭头函数,接下来又是一个类型判断,不通过就报错。 最后返回由工具函数mapValue处理后的actionCreators对象。 本节比较水。。。。。