mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
editing begin
This commit is contained in:
@@ -2,13 +2,23 @@ import { Reducer } from 'redux';
|
||||
import { ActionTypes, TodoAction } from '../actions';
|
||||
import { Draft, produce } from 'immer';
|
||||
|
||||
export function createReducer<T>(
|
||||
initialState: T,
|
||||
handlers: { [actionType in ActionTypes]?: (state: Draft<T>, action: TodoAction) => T }
|
||||
): Reducer<T> {
|
||||
export type ImmerReducer<T> = (state: Draft<T>, action: TodoAction) => T;
|
||||
export type HandlerMap<T> = { [actionType in ActionTypes]?: ImmerReducer<T> };
|
||||
|
||||
function isHandlerFunction<T>(handlerOrMap: HandlerMap<T> | ImmerReducer<T>): handlerOrMap is ImmerReducer<T> {
|
||||
if (typeof handlerOrMap === 'function') {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
export function createReducer<T>(initialState: T, handlerOrMap: HandlerMap<T> | ImmerReducer<T>): Reducer<T> {
|
||||
return function reducer(state = initialState, action: TodoAction): T {
|
||||
if (handlers.hasOwnProperty(action.type)) {
|
||||
return produce(state, draft => handlers[action.type](draft, action));
|
||||
if (isHandlerFunction(handlerOrMap)) {
|
||||
return produce(state, draft => handlerOrMap(draft, action));
|
||||
} else if (handlerOrMap.hasOwnProperty(action.type)) {
|
||||
return produce(state, draft => handlerOrMap[action.type](draft, action));
|
||||
} else {
|
||||
return state;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user