redux API bindActionCreators使用
bindActionCreators(actionsCreators,dispatch)
bindActionCreators的原理
function bindActionCreators(actionCreators,dispatch) {
    let obj = {};
    for(let i in actionCreators) {
        obj[i] = function() {
            dispatch(actionCreators[i]);
        }
    }
    return obj;
}
ActionCreators.js
export function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  }
}
export function removeTodo(id) {
  return {
    type: 'REMOVE_TODO',
    id
  }
}
针对ActionCreators不使用bindActionCreators的话,我们需要这样写多个dispatch,如果太多的话就会很麻烦
const mapDispatchToProps = (dispatch) => {
  return {
    addTodo: (text) => {
      dispatch(TodoActionCreators.addTodo(text))
    },
    removeTodo: (id) => {
      dispatch(TodoActionCreators.removeTodo(id))
    }
   }
};
使用bindActionCreators
bindActionCreators是redux的一个自带函数,作用是将单个或多个ActionCreator转化为dispatch(action)的函数集合形式。
开发者不用再手动dispatch(actionCreator(type)),而是可以直接调用方法。
可以实现简化书写,减轻开发的负担。
const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(ActionCreators, dispatch);
};
调用dispatch方法:
  this.props.addTodo(test)、this.props.removeTodo(test);
总结:bindActionCreators将单个或多个ActionCreator转化为dispatch(action)的函数集合形式,不用写多个dispatch
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号