Redux源码解读--(3)bindActionCreators

首先看一下函数的使用场景:

@connect(
    state => {
        const {  } = state;
        return {  }
    },
    dispatch => ({
        actions: bindActionCreators({ ...actions, ...otheractions }, dispatch)
    })
)
没错,就是配合connect使用的函数。他接收actions的集合和一个dispatch作为参数,效果说白了就是用dispatch给action包起来了。

function bindActionCreator(actionCreator, dispatch) {
  return (...args) => dispatch(actionCreator(...args))
}
export default function bindActionCreators(actionCreators, dispatch) {
  if (typeof actionCreators === 'function') {  //官方解释为:你可以只传入一个函数为参数,他会给这个函数的返回结果添加diapatch处理。
    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 = {}
  for (let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const actionCreator = actionCreators[key]   //根据传入参数的key获得value,actionCreator,顾名思义,返回action的函数。
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }  //
  }
  return boundActionCreators   //为其添加dispatch并返回。
}
由上述代码可知:我传入的...actions,应该为   xxx:createAction("XXXXXX")

或者   xxx = createAction("XXXXXX"),这个时候只要传一个xxx就可以了。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值