react-redux中connect中的mapDispatchToProps疑惑

代码一:

import { addTodo } from './actionCreators'
import { bindActionCreators } from 'redux'

function mapStateToProps(state) {
  return { todos: state.todos }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addTodo }, dispatch)
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)

代码二:

import { addTodo } from './actionCreators'

function mapStateToProps(state) {
  return { todos: state.todos }
}

const mapDispatchToProps = {
  addTodo
}

export default connect(mapStateToProps, mapDispatchToProps)(TodoApp)

以上两段代码的作用都是注入 todos 和特定的 action 创建函数,有一点疑惑的地方
代码一中调用了bindActionCreators 而代码二中没有调用,两段代码出来的效果都是一样的。
请问bindActionCreators 的作用是什么?

阅读 840
评论
    1 个回答
    • 336
    function bindActionCreator(actionCreator, dispatch) {
      return (...args) => dispatch(actionCreator(...args));
    }
    
    /*
     * @param actionCreators
     * @param dispatch
     * @return {actionKey: (...args) => dispatch(actionCreator(...args))}
     */
    export default function bindActionCreators(actionCreators, dispatch) {
      return mapValues(actionCreators, actionCreator =>
        bindActionCreator(actionCreator, dispatch)
      );
    }

    bindActionCreators部分源码,再里面调用了dispatch方法

      撰写回答

      登录后参与交流、获取后续更新提醒