bindActionCreators
通过 ActionCreator 创建动作
- 字面意思 是一个
action
的创造者 - 比如我们可以通过函数 传递不同的参数 创建不同参数的
action
比如我们想根据不同参数生成不同步长的计数器动作 - 随着我们的业务逻辑越来越复杂 我们可以通过定义更加复杂的工厂函数来生成更多样化的
action
const counterIncActionCreator = function (step?: number) {
return {
type: "INCREMENT",
step: step || 1,
};
};
bindActionCreator (简介)
- 基于上面的代码 如果我们想创建出不同步长的计数器
action
并且分发这些创建的action
代码如下
const action1 = counterIncActionCreator();
dispatch(action1);
// { type: 'INCREMENT', step: 1 }
const action2 = counterIncActionCreator(2);
dispatch(action2);
// { type: 'INCREMENT', step: 2 }
const action3 = counterIncActionCreator(3);
dispatch(action3);
// { type: 'INCREMENT', step: 3 }
- 每次分发动作之前我们都得手动调用
counterIncActionCreator
来生产相应的动作,这种方式并不是那么的优雅 - 我们可以自己用一个
bindActionCreator
函数代替这部分操作
function bindActionCreator(actionCreator, dispatch) {
return function (this, ...args: any[]) {
return dispatch(actionCreator.apply(this, args));
};
}
bindActionCreator
将会返回一个新函数 这个函数会用自身所接收的参数来调用 actionCreator 生成一个Action
- 我们把
生成 action
和调度 action
这个两个步骤放在同一个步骤里面了 使用方法如下
const increment = bindActionCreator(counterIncActionCreator, dispatch);
increment(1);
// { type: 'INCREMENT', step: 1 }
increment(2);
// { type: 'INCREMENT', step: 2 }
increment(3);
// { type: 'INCREMENT', step: 3 }
bindActionCreators
bindActionCreators
实际上就是加强版的 bindActionCreator主要区别在于
bindActionCreators可以处理多个
action 函数`
function bindActionCreator(actionCreator, dispatch) {
return function (this, ...args: any[]) {
return dispatch(actionCreator.apply(this, ...args));
};
}
const 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, but instead received: '${kindOf(
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;
};
bindActionCreators 使用。
const actionCreators = {
increment: function (step) {
return {
type: "INCREMENT",
step: step || 1,
};
},
decrement: function (step) {
return {
type: "DECREMENT",
step: -(step || 1),
};
},
};
const newActionCreators = bindActionCreators(actionCreators, dispatch);
newActionCreators.increment(1);
// {type: "INCREMENT", step:1}
newActionCreators.decrement(2);
// {type: "DECREMENT", step:-2}