1,分析
一般情况下,action
并不是一个写死的对象,而是通过函数来获取。
而 bindActionCreators
的作用:为了更方便的使用创建 action
的函数 actionCreator
。
举例:
1,直接传入函数
const createAddUserAction = (user) => ({
type: ADD_USER,
payload: user,
});
store.dispatch(createAddUserAction({ id: 3, name: "name3", age: 20 }));
相当于
const addUser = bindActionCreators(createAddUserAction, store.dispatch);
addUser({ id: 3, name: "name3", age: 20 });
2,传入对象
const actions = {
addUser: createAddUserAction,
updateUser: createUpdateUserAction,
deleteUser: createDeleteUserAction,
};
store.dispatch(actions.addUser({ id: 3, name: "name3", age: 20 }));
store.dispatch(actions.updateUser(2, { name: "name22" }));
store.dispatch(actions.deleteUser(1));
相当于
const bindAction = bindActionCreators(actions, store.dispatch);
bindAction.addUser({ id: 3, name: "name3", age: 20 });
bindAction.updateUser(2, { name: "name22" });
bindAction.deleteUser(1);
2,实现
export const bindActionCreators = (actionCreators, dispatch) => {
if (typeof actionCreators === "function") {
return getAutoDispatchActionCreator(actionCreators, dispatch);
} else if (typeof actionCreators === "object") {
const res = {};
for (const key in actionCreators) {
if (Object.hasOwnProperty.call(actionCreators, key)) {
const ac = actionCreators[key];
if (typeof ac === "function") {
res[key] = getAutoDispatchActionCreator(ac, dispatch);
}
}
}
return res;
} else {
throw TypeError("actionCreators 必须是函数或对象");
}
};
function getAutoDispatchActionCreator(actionCreator, dispatch) {
return function (...args) {
dispatch(actionCreator(...args));
};
}
以上。