Redux 따라하기
강의 에제
Store 폴더
export type Action<Payload> = {
type: string;
payload?: Payload;
};
type Reducer<State, Payload> = (state: State, action: Action<Payload>) => State;
type Listener = () => void;
type Reducers<State> = Record<string, Reducer<State, any>>;
export default class BaseStore<State> {
state: State;
reducer: Reducer<State, any>;
listeners = new Set<Listener>();
constructor(initialState: State, reducers: Reducers<State>) {
this.state = initialState;
this.reducer = (state: State, action: Action<any>) => {
const reducer = Reflect.get(reducers, action.type);
if (!reducer) {
return state;
}
return reducer(state, action);
};
}
// Dispatch는 액션을 받는다.
dispatch(action: Action<any>) {
// Reducer를 실행해준다. 그러면 새로운 state가 나옴
this.state = this.reducer(this.state, action);
// 그러고 나서 publish하면 된다.
this.publish();
}
publish() {
this.listeners.forEach(listener => {
listener();
});
}
addListener(listener: () => void) {
this.listeners.add(listener);
}
removeListener(listener: () => void) {
this.listeners.delete(listener);
}
}
hooks 폴더
Components 폴더
Last updated