bindActionCreators

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

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

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

    例如:spa

    actionCreator.js以下:code

    复制代码
    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的一个对象blog

    通过bindActionCeators的处理变为:开发

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

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

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

    一般用在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

相关文章
相关标签/搜索