Redux 源码解读之 bindActionCreators

本文深入解析了Redux源码中的bindActionCreators功能,该函数能够将action creators转换为带有dispatch绑定的同名对象,便于组件调用。适用于子组件无需直接接触Redux场景,简化了dispatch的传递。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


bindActionCreator 源码地址:node_modules/redux/src/bindActionCreators.js。
bindActionCreators 的功能是将第一个参数对象转换为同名 key 对象,然后可以很方便地使用 dispatch。

一、将参数对象转换为同名 key 对象

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 boundActionCreators = {}
  for (const key in actionCreators) {
    const actionCreator = actionCreators[key]
    if (typeof actionCreator === 'function') {
      boundActionCreators[key] = bindActionCreator(actionCreator, dispatch)
    }
  }
  return boundActionCreators
}
  1. 如果参数 actionCreators 类型为 function,则直接执行这个函数。
  2. 如果参数 actionCreators 类型不是非 null 的对象,抛错;
  3. 如果参数 actionCreators 类型为非 null 对象,则浅复制一份给变量 boundActionCreators。返回值为 boundActionCreators 。其目的是将参数对象转换成一个同名 key 对象。

二、应用场景

当你需要将 actions 传给子组件,但是又不想子组件有任何 Redux 的存在,或者不行层层传递 dispatch 时 。可以使用 bindActionCreators。

actions:

export function addTodo(text) {
  return {
    type: 'ADD_TODO',
    text
  };
}
export function removeTodo(id) {
  return {
    type: 'REMOVE_TODO',
    id
  };
}

App:

class App extends React.Component { 
  constructor(props) {
        super(props);
 }
  render() {
        const {addTodo} = this.props;     
        return <div>
            <Item {...actions}/>
  }
};
const mapDispatchToProps = (dispatch)=>{
    return {       
actions:bindActionCreators({addTodo,removeTodo},dispatch)
    }
};
export default connect(state=>(state),mapDispatchToProps)(App);

Item:

class Item extends React.Component {
       render() {
        const {addTodo,removeTodo} = this.props;       
        return <div onClick={()=>{console.log(addTodo(1))}}>点击试试看</div>
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值