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

相關文章
相關標籤/搜索