Tina

리덕스 공부

밍밍이

밍밍이

Nov 20, 2020

관리할 상태 정의 - module/todo.js

const initialState = [
{
id: 1,
text: '예시',
done: false
}
]

액션 타입 정의(대문자) - module/todo.js

const ADD_TODO = 'todos/ADD_TODO';
const TOGGLE_TODO = 'todos/TOGGLE_TODO';

액션 생성함수 정의 - module/todo.js

let nextId = 1;
export const addTodo = text => ({
type: ADD_TODO,
todo: {
id: nextId++,
text
}
});
export const toggleTodo = id => ({
type: TOGGLE_TODO,
id
});

리듀서 만들기 - module/todo.js

export default function todos(state = initialState, action){
switch(action.type){
case ADD_TODO:
return state.concat(action.todo);
case TOGGLE_TODO:
return state.map(
todo =>
todo.id === action.id?
{...todo, done: !todo.done } : todo
);
default:
return state;
}
}

스토어 만들기 : 리듀서 주입 - index.js

디스패치 - containers/TodosContainer.js

const store = createStore(rootReducer);
const dispatch = useDispatch();
const onIncrease = () => dispatch(increase());
const onDecrease = () => dispatch(decrease());
const onSetDiff = diff => dispatch(setDiff(diff));

그외

  • 리스너 함수 : 스토어 내 상태가 바뀔때마다 호출
  • 구독해제 : store.unsubscribe(listener)