Redux 기초 - 바닐라 자바스크립트에서 리덕스 사용해보기2
포스트
취소

Redux 기초 - 바닐라 자바스크립트에서 리덕스 사용해보기2

노마드코더 - 초보자를 위한 리덕스 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));
};

출처) 노마드코더 - 초보자를 위한 리덕스 101


이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.