티스토리 뷰
Part 3. Redux 만들기 -
01. 문제 정의 - 어떤 코드가 상태를 어디서 바꾸나?
*참조사이트: https://v2.grommet.io/components
->기본적인 레이아웃과 주요하게 많이 쓰이는 'components'들을 'React' 버전으로 제공
*참조사이트: https://www.npmjs.com/package/uuid
-> 간단하게 유니크한 문자열을 만드는 패키지 정리된 사이트
*참조사이트: https://styled-components.com/
-> 간단하게 css 스타일링을 해야 되는 필요성이 생길 때 필요한 사이트
02. 해결책 만들기
*참조사이트: https://facebook.github.io/flux/docs/in-depth-overview/
*참조사이트: https://redux.js.org/
->Redux Toolkit로 여러가지 편리한 기능들을 사용할 수 있게끔 디자인되어 있음
03. 구독 발행 모델
app.js
->
function createStore() {
let state;
let handlers = [];
function send(action){
state = worker(state, action);
handlers.forEach(handler => handler());
}
function subscribe(handler){
handlers.push(handler);
}
function getState() {
return state;
}
return{
send,
getState,
subscribe,
};
}
function worker(state = {count: 0 }, action) {
switch(action.type){
case 'increase':
return { ...state, count: state.count + 1 };
default:
return { ...state };
}
}
const store = createStore(worker);
store.subscribe(function(){
console.log(store.getState());
});
store.send({ type: 'increase' });
store.send({ type: 'increase' });
store.send({ type: 'increase' });
04. 그럴듯 하게 모양내기
app.js
->
import { createStore, actionCreator } from './redux.js';
import { reducer } from './reducer.js';
import * as Actions from './actions.js';
const store = createStore(reducer);
store.subscribe(function(){
console.log(store.getState());
});
store.dispath(Actions.increase());
store.dispath(Actions.increase());
store.dispath(Actions.increase());
store.dispath(Actions.decrease());
store.dispath(Actions.reset());
actions.js
->
import { actionCreator } from './redux.js';
import { INCREASE, DECREASE, RESET } from './action-type.js';
export const increase = actionCreator(INCREASE);
export const decrease = actionCreator(DECREASE);
export const reset = actionCreator(RESET);
reducer.js
->
import * as ActionType from './action-type.js';
const InitializeState = { count : 0};
export function reducer(state = InitializeState, action) {
switch(action.type){
case ActionType.INCREASE:
return { ...state, count: state.count + 1 };
default:
return { ...state };
case ActionType.DECREASE:
return { ...state, count: state.count - 1 };
default:
return { ...state };
case ActionType.RESET:
return { ...state, count: 0 };
default:
return { ...state };
}
}
redux.js
->
export const actionCreator = type => payload => {{
type,
payload,
}};
export function createStore(reducer) {
let state;
let handlers = [];
function dispath(action){
state = reducer(state, action);
handlers.forEach(handler => handler());
}
function subscribe(handler){
handlers.push(handler);
}
function getState() {
return state;
}
return{
dispath,
getState,
subscribe,
};
}
action-type.js
->
export const INCREASE = 'increase';
export const DECREASE = 'decrease';
export const RESET = 'reset';