노마드코더 - 초보자를 위한 리덕스 101을 듣고 정리한 내용입니다.
state Mutation
- Redux에서는 state를 직접 변경하면 안된다.
참고) redux 공식문서 - do not mutate state
(공식 문서에 다르면 state를 직접 변경하게 되면 컴포넌트가 제대로 렌더링되지 않을 수도 있고, 디버깅을 중단시킬 수 있다고 한다.) - 항상 새 state를 return해야 한다. state를 복사해서 복사한 값을 변경해서 return하는 방법을 사용할 수 있다.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const reducer = (state = [], action) => {
switch (action.type) {
case ADD_TODO:
const newToDoObj = { text: action.text, id: Date.now() };
// spread 연산자를 사용해서 새로운 배열을 return한다.
return [newToDoObj, ...state];
case DELETE_TODO:
// filter함수를 사용해서 새로운 배열을 return한다.
const cleand = state.filter((toDo) => toDo.id !== action.id);
return cleand;
default:
return state;
}
};
Action Creators
- dispatch의 인자로 전달하는 객체를 return하는 함수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { createStore } from "redux";
const ADD_TODO = "ADD_TODO";
const DELETE_TODO = "DELETE_TODO";
// Action Creators
const addToDo = (text) => {
return { type: ADD_TODO, text };
};
const deleteToDo = (id) => {
return { type: DELETE_TODO, id };
};
const dispatchAddToDo = (text) => {
store.dispatch(addToDo(text));
};
const dispatchDeleteToDo = (e) => {
const id = parseInt(e.target.parentNode.id);
store.dispatch(deleteToDo(id));
};