我正在制作一个关于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);
}
}
但我不知道我们将state
和action
传递到哪里并调用combineReducers
返回的函数?
非常感谢有人会清除这一点,并显示实际通话的位置。