Redux 源碼解析系列(二)-- bindActionCreator

bindActionCreator 的做用其實就是用來將一個對象的值是action creators轉成一個一樣key的對象,可是轉化的這個對象的值,是將action creator包裹在dispatch裏的函數。函數

也就是說,假設下面的actionCreator.js 咱們import進來這個對象spa

export function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  }
}

export function removeTodo(id) {
  return {
    type: 'REMOVE_TODO',
    id
  }
}

獲得的對象爲code

{
   addTodo : text => 
    { 
      type: 'ADD_TODO',
      text
    },
   removeTodo : id => {
      type: 'REMOVE_TODO',
      id
    }
}

通過bindActionCreator就會變成對象

{
   addTodo : text => dispatch(addTodo('text'));
   removeTodo : id => dispatch(removeTodo('id'));
}

至關於會dispatch這個action。rem

參數:
一、actionCretors 能夠是一個對象,也能夠是一個單個函數
二、dispatch函數it

返回:
單個函數,或者是一個對象。io

傳入一個function

若是隻是傳入一個function,返回的也是一個functionfunction

例如:import

const toggleTodo = (id) => {
    return {
        type: 'TOGGLE_TODO',
        id
    };
};

export { toggleTodo };
let boundActionCreators = bindActionCreators(toggleTodo, dispatch);

//此時boundActionCreators  = (id) => dispatch(toggleTodo(id));

因此bindActionCreator比較簡單:
一、判斷傳入的參數是不是object,若是是函數,就直接返回一個包裹dispatch的函數
二、若是是object,就根據相應的key,生成包裹dispatch的函數便可object

function bindActionCreator(actionCreator, dispatch) {
  return function() { return dispatch(actionCreator.bind(undefined, arguments))}
}
function bindActionCreator(actionCreator, dispatch) {
 
  return function() { return dispatch(actionCreator.bind(undefined, 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 = {}
   keys.forEach((key) => {
     boundActionCreators[key] = bindActionCreator(actionCreators[key], dispatch)
   })
   return boundActionCreators
}

總結,bindActionCreator 的做用就是返回包裹dispatch的函數能夠直接使用。通常咱們會用來mapDispatchToProps裏。

相關文章
相關標籤/搜索