手写bindActionCreators

export default function bindActionCreators(actionCreators, dispatch) {
    //actionCreators是函数的情况下
    if (typeof actionCreators === "function") {
        return getAutoDispatchActionCreator(actionCreators, dispatch)
    }
    //actionCreators是对象的情况下
    else if (typeof actionCreators === "object") {
        const result = {}
        for (const key in actionCreators) {
            console.log(key);
            if (actionCreators.hasOwnProperty(key)) {
                const currentAction = actionCreators[key];
                //函数的情况下执行
                if (typeof currentAction === "function") {
                    result[key] = getAutoDispatchActionCreator(currentAction, dispatch)
                }
            }
        }
        return result;
    }
    else {
        throw new TypeError("must be function or object")
    }
}
//辅助函数,增强自动分发dispatch函数
function getAutoDispatchActionCreator(actionCreator, dispatch) {
    return function (...args) {
        console.log(...args);
        const action = actionCreator(...args)
        dispatch(action);
    }
}

 

posted @ 2021-01-05 17:30  漫漫长路上的求知者  阅读(78)  评论(0编辑  收藏  举报