bindActionCreators

  • bindActionCreators是redux的一个API,作用是将单个或多个ActionCreator转化为dispatch(action)的函数集合形式。

    开发者不用再手动dispatch(actionCreator(type)),而是可以直接调用方法。

    目的就是简化书写,减轻开发负担。

    例如:

    actionCreator.js如下:

    复制代码
    export function addTodo(text) {
      return {
        type: 'ADD_TODO',
        text
      }
    }
    
    export function removeTodo(id) {
      return {
        type: 'REMOVE_TODO',
        id
      }
    }
    复制代码

    导出的对象为:

    复制代码
    {
       addTodo : text => 
        { 
          type: 'ADD_TODO',
          text
        },
       removeTodo : id => {
          type: 'REMOVE_TODO',
          id
        }
    }
    复制代码

    是以函数名为key,函数为value的一个对象

    经过bindActionCeators的处理变为:

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

    是以函数名为key,内部执行dispatch(action)的函数为value的对象,用这个对象就可以直接调用方法了,不必手动dispatch

    如果传入单个actionCreator,则返回的是一个包裹dispatch的函数,而不是一个对象。

    通常用在mapDispatchToProps中,向组件传递action方法:

    export default connect(
        (state,props) => { return {data: state.article.data,currentCate:fCurrentCate(state,props)} },
        dispatch => { return {actions: bindActionCreators(acts,dispatch)} }
    )(Article);

    通过actions对象调用方法,就可以dispatch所有的action

    参考:https://segmentfault.com/a/1190000011783611

猜你喜欢

转载自www.cnblogs.com/ssw-men/p/11387182.html