CódigoNão tentada
combineReducers
Dificuldade: média
Combine reducers de slices em um único reducer raiz cujo state é indexado por slice. Slices que não mudaram mantêm sua referência, e se nada mudou, retorne o mesmo objeto raiz para que as checagens com === mais adiante possam abortar.
Ver solução de referência
type Reducer<S = any> = (state: S | undefined, action: { type: string }) => S;
export function combineReducers(reducers: Record<string, Reducer>): Reducer<Record<string, any>> { return function (state = {}, action) { const nextState: Record<string, any> = {}; let changed = false; for (const key in reducers) { nextState[key] = reducers[key](state[key], action); // each reducer only sees its own slice if (nextState[key] !== state[key]) { changed = true; } } // Nothing changed: return the old object, so `===` checks in components still pass. return changed ? nextState : state; };}
Ctrl Enter