[email protected](57)[email protected](6)- 实现 bindActionCreators

目录

1,分析

一般情况下,action 并不是一个写死的对象,而是通过函数来获取。

bindActionCreators 的作用:为了更方便的使用创建 action 的函数 actionCreator

举例:

1,直接传入函数

js 复制代码
const createAddUserAction = (user) => ({
    type: ADD_USER,
    payload: user,
});

store.dispatch(createAddUserAction({ id: 3, name: "name3", age: 20 }));

相当于

js 复制代码
const addUser = bindActionCreators(createAddUserAction, store.dispatch);
addUser({ id: 3, name: "name3", age: 20 });

2,传入对象

js 复制代码
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));

相当于

js 复制代码
const bindAction = bindActionCreators(actions, store.dispatch);
bindAction.addUser({ id: 3, name: "name3", age: 20 });
bindAction.updateUser(2, { name: "name22" });
bindAction.deleteUser(1);

2,实现

js 复制代码
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));
    };
}

以上。

相关推荐
不爱吃饭爱吃菜1 小时前
uniapp微信小程序一键授权登录
前端·javascript·vue.js·微信小程序·uni-app
heart000_11 小时前
从零开始打造个人主页:HTML/CSS/JS实战教程
javascript·css·html
90后小陈老师2 小时前
3D个人简历网站 5.天空、鸟、飞机
前端·javascript·3d
chenbin___2 小时前
react native text 显示 三行 超出部分 中间使用省略号
javascript·react native·react.js
漫路在线5 小时前
JS逆向-某易云音乐下载器
开发语言·javascript·爬虫·python
不爱吃糖的程序媛5 小时前
浅谈前端架构设计与工程化
前端·前端架构设计
BillKu7 小时前
Vue3 Element Plus 对话框加载实现
javascript·vue.js·elementui
郝YH是人间理想7 小时前
系统架构设计师案例分析题——web篇
前端·软件工程
Evaporator Core7 小时前
深入探索:Core Web Vitals 进阶优化与新兴指标
前端·windows
初遇你时动了情8 小时前
html js 原生实现web组件、web公共组件、template模版插槽
前端·javascript·html