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;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createReducer } from './createReducer';
|
||||
import { Store, FilterTypes } from '../store';
|
||||
import { combineReducers } from 'redux';
|
||||
import produce from 'immer';
|
||||
|
||||
let counter = 0;
|
||||
|
||||
@@ -22,12 +23,19 @@ export const reducer = combineReducers<Store>({
|
||||
complete(draft, action) {
|
||||
draft[action.id].completed = !draft[action.id].completed;
|
||||
return draft;
|
||||
},
|
||||
|
||||
clear(draft, action) {
|
||||
Object.keys(draft).forEach(id => {
|
||||
if (draft[id].completed) {
|
||||
delete draft[id];
|
||||
}
|
||||
});
|
||||
return draft;
|
||||
}
|
||||
}
|
||||
),
|
||||
filter: createReducer<FilterTypes>('all', {
|
||||
filter(draft, action) {
|
||||
return action.filter;
|
||||
}
|
||||
filter: createReducer<Store['filter']>('all', (draft, action) => {
|
||||
return action.filter;
|
||||
})
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user