Redux - 理解结合减速器

时间:2018-03-16 23:49:33

标签: javascript redux functional-programming

我正在制作一个关于Redux的教程,我正在尝试找出这段代码:

export const combineReducers = (config) =>{
    return (state, action) => {
        return Object.keys(config).reduce((state, key) => {
            const reducer = config[key];
            const previousState = state.get(key);
            const newValue = reducer(previousState, action);

            if (!newValue) {
                throw new Error(`A reducer returned undefined when reducing key::"${key}"`);
            }
            return state.set(key, newValue);
        }, state);
    }
}

我想弄清楚的是,这一切是如何联系起来的。我在index.js文件夹中有一个reducers文件,调用combineReducers

export const reducer = combineReducers({
    currentUser
});

我作为配置参数传递的currentUser如下所示:

export const currentUser = createReducer(null, {
    [UPDATE_STATUS](state,action) {
        return state.set(`status`,action.status);
    }
});

这是createReducer函数:

export const createReducer = (initialState, handlers)=>{
    return function reducer(state = initialState, action) {
        if (handlers.hasOwnProperty(action.type)) {
            return handlers[action.type](state, action)
        } else {
            return state
        }
    }
}

因此,我们将返回reducer函数的createReducer传递给combineReducers。所以,在这一点上,我们最终会得到这样的假设:

export const combineReducers = (config) =>{
    // this is just for demonstration purposes, to show what I assume ends up as a config argument
    // config = {
    //     currentUser: function reducer(state = initialState, action) {
    //                     if (handlers.hasOwnProperty(action.type)) {
    //                         return handlers[action.type](state, action)
    //                     } else {
    //                         return state
    //                     }
    //                 }
    //  }
    // where function reducer has access to parameters that were passed previously
    // initialState = null
    // handlers = {
    //     [UPDATE_STATUS](state,action) {
    //         return state.set(`status`,action.status);
    //      }
    //  }

    return (state, action) => {
        return Object.keys(config).reduce((state, key) => {
            const reducer = config[key];
            const previousState = state.get(key);
            const newValue = reducer(previousState, action);

            if (!newValue) {
                throw new Error(`A reducer returned undefined when reducing key::"${key}"`);
            }
            return state.set(key, newValue);
        }, state);
    }
}

但我不知道我们将stateaction传递到哪里并调用combineReducers返回的函数? 非常感谢有人会清除这一点,并显示实际通话的位置。

0 个答案:

没有答案