Redux 따라하기
dispatch를 받고 selector를 이용해서 상태를 얻을 수 있다.
dispatch에 액션을 던져준다.(객체로)
external store는 순수한 자바스크립트에 가깝기 때문에 테스트하기 쉽다.
쉬린지는 객체만 넘겨줄수가 있다.
실제로 리덕스 써보면 컨텍스트로 스토어를 만들어서 넘겨줄 수 있다.
강의 에제
Store 폴더
BaseStore.ts
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);
}
}
store.ts
hooks 폴더
useDispatch.ts
useForceUpdate.ts
useSelector.ts
Components 폴더
CountControl.tsx
Counter.tsx
NameCard.tsx
Last updated