mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
integrating immer
This commit is contained in:
@@ -1,13 +1,14 @@
|
||||
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: T, action: TodoAction) => T }
|
||||
handlers: { [actionType in ActionTypes]?: (state: Draft<T>, action: TodoAction) => T }
|
||||
): Reducer<T> {
|
||||
return function reducer(state = initialState, action: TodoAction): T {
|
||||
if (handlers.hasOwnProperty(action.type)) {
|
||||
return handlers[action.type](state, action);
|
||||
return produce(state, draft => handlers[action.type](draft, action));
|
||||
} else {
|
||||
return state;
|
||||
}
|
||||
|
||||
@@ -5,17 +5,23 @@ import { combineReducers } from 'redux';
|
||||
let counter = 0;
|
||||
|
||||
export const reducer = combineReducers<Store>({
|
||||
todos: createReducer(
|
||||
todos: createReducer<Store['todos']>(
|
||||
{},
|
||||
{
|
||||
add(state, action) {
|
||||
add(draft, action) {
|
||||
const id = String(counter++);
|
||||
return { ...state, [id]: { label: action.label, completed: false } };
|
||||
draft[id] = { label: action.label, completed: false };
|
||||
return draft;
|
||||
},
|
||||
|
||||
remove(draft, action) {
|
||||
delete draft[action.id];
|
||||
return draft;
|
||||
}
|
||||
}
|
||||
),
|
||||
filter: createReducer<FilterTypes>('all', {
|
||||
filter(state, action) {
|
||||
filter(draft, action) {
|
||||
return action.filter;
|
||||
}
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user