redux的bindActionCreators源碼,中文翻譯

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...redux

相關文章
相關標籤/搜索