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

bindActionCreator 的作用其实就是用来将一个对象的值是action creators转成一个同样key的对象,但是转化的这个对象的值,是将action creator包裹在dispatch里的函数。

也就是说,假设下面的actionCreator.js 我们import进来这个对象

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
    }
}

经过bindActionCreator就会变成

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

相当于会dispatch这个action。

参数:
1、actionCretors 可以是一个对象,也可以是一个单个函数
2、dispatch函数

返回:
单个函数,或者是一个对象。

传入一个function

如果只是传入一个function,返回的也是一个function

例如:

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

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

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

所以bindActionCreator比较简单:
1、判断传入的参数是否是object,如果是函数,就直接返回一个包裹dispatch的函数
2、如果是object,就根据相应的key,生成包裹dispatch的函数即可

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里。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值