1
bindActionCreators就是给action创建函数绑定了dispatch,
可以直接以普通函数执行,而不用dispatch(actionCreator)这样写.
比如下面,bindActionCreators生成一个对象,对象里面的value值是function,
那么可以直接this.boundActionCreators.addTodo()执行**

clipboard.png

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

/**
 * Turns an object whose values are action creators, into an object with the
 * same keys, but with every function wrapped into a `dispatch` call so they
 * may be invoked directly. This is just a convenience method, as you can call
 * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.
 *
 * 将一个value值是action创建函数的对象变成一个具有相同key值的对象,但是每个函数都被封装到
 * `dispatch`回调里面,这样它们就有可能被直接触发. 这样只是比较方便,你也可以调用
 * `store.dispatch(MyActionCreators.doSomething())`
 * 
 * For convenience, you can also pass a single function as the first argument,
 * and get a function in return.
 *
 * 为了方便,你也可以传单个函数作为第一个参数,然后返回一个函树
 * 
 * @param {Function|Object} actionCreators An object whose values are action
 * creator functions. One handy way to obtain it is to use ES6 `import * as`
 * syntax. You may also pass a single function.
 *
 * actionCreators 是一个value值是action创建函数的对象,一个很方便获取到它的方法就是
 * 使用ES6 的`import * as `语法.也可以传单个函数
 * 
 * @param {Function} dispatch The `dispatch` function available on your Redux
 * store.
 *
 * dispatch就是redux 里store的dispatch
 * 
 * @returns {Function|Object} The object mimicking the original object, but with
 * every action creator wrapped into the `dispatch` call. If you passed a
 * function as `actionCreators`, the return value will also be a single
 * function.
 * 
 * 返回的对象和初始的对选象很像,但每一个action创建函数都给封装到`dispatch`回调里面
 * 如果你传单个函数作为`actionCreators`,那返回值也是一个单个函数
 */
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"?`
    )
    //bindActionCreators的参数应该是对象或者函数,而不是空或其他类型,
    //你是不是把"import * as ActionCreators from"写成了"import 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) //就是(...args) => dispatch(actionCreator(...args))
    }
  }
  return boundActionCreators
}

源码解析请参考https://segmentfault.com/a/11...


杨柳岸残月孤轮
44 声望1 粉丝