[Redux] Implementing combineReducers() from Scratch

时间:2022-06-12 20:02:45

The combineReducers function we used in previous post:

const todoApp = combineReducers({
todos,
visibilityFilter
});
  • It accepts and object as agruement;
  • It returns an function

Implemente by ourself:

 // reducers: {todos: todos, filter: filter}
const combineReducers = (reducers) => {
// return a reducer function
return (state={},action)=>{
// combine the reducers
return Object.keys(reducers)
.reduce( (acc, curr)=>{
acc[curr] = reducers[curr](
state[curr],
action
); // todos: todos return acc;
}, {})
}
};