Study/Redux

[Redux] #1.2 Actions ~ #1.4 Recap Refactor

yujin2 2021. 3. 3. 10:31

초보자를 위한 리덕스 101을 바탕으로 작성했습니다.

 

 

Actions

import { createStore } from "redux";

const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");

const countModifier = (count = 0, action) => {
  return count;
};

const countStore = createStore(countModifier); // createStore은 우리에게 reducer를 주기를 요구함. reducer는 function이어야 함
console.log(countStore.getState());

count를 action을 이용하여 modify 할 수 있다

action은 redux에서 function을 부를 때 쓰는 두번째 parameter(argument)이다

 

import { createStore } from "redux";

const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");

const countModifier = (count = 0, action) => {
  if (action.type === "ADD") {
    return count + 1;
  } else if (action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(countModifier); // createStore은 우리에게 reducer를 주기를 요구함. reducer는 function이어야 함

countStore.dispatch({ type: "ADD" });
countStore.dispatch({ type: "MINUS" });
console.log(countStore.getState());

dispatch() 를 통해 countModifier에게 action을 보낼 수 있다

위 상황에서 Redux는 countModifier(currentState = 0, { type: "ADD" }); 로 메세지를 보내게 된다

ADD 한 번, MINUS 한 번 전송되므로 count가 0 -> 1 -> 0 으로 바뀌어 콘솔에는 0이 출력된다

 

data의 store을 만들고 -> data의 modifier을 매개변수로 전달해주고 -> dispatch 통해 message를 store에 전송

전송한 message는 action에 넣으면 되고, 할 일은 action을 체크해보면 됨

 

 

 

Subscriptions

import { createStore } from "redux";

const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");

number.innerText = 0;

const countModifier = (count = 0, action) => {
  if (action.type === "ADD") {
    return count + 1;
  } else if (action.type === "MINUS") {
    return count - 1;
  } else {
    return count;
  }
};

const countStore = createStore(countModifier); // createStore은 우리에게 reducer를 주기를 요구함. reducer는 function이어야 함

const onChange = () => {
  number.innerText = countStore.getState();
};

countStore.subscribe(onChange);

const handleAdd = () => {
  countStore.dispatch({ type: "ADD" });
};
const handleMinus = () => {
  countStore.dispatch({ type: "MINUS" });
};

add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

subscribe는 store 안에 있는 변화들을 알 수 있게 해준다

위 코드에서 store에 변화가 있을 때마다 onChange 함수가 감지되어 불려진다

data를 수정하는 유일한 곳은 Reducer 안이고, Redux는 이런 식으로 작동된다

 

 

 

Recap Refactor

정리

✔️ Reducer는 현재 stateaction과 함께 불려지는 function

✔️ Reducer가 리턴하는 것은 application의 state가 됨

✔️ Reducer에게 action을 보내는 방법은 dispatch (dispatch는 Reducer 불러서 current state과 action을 더함)

✔️action은 modifier와 소통하는 방법으로, 무조건 type을 가져야 하고 object이어야 함

✔️ 변화를 store에서 감지하고 싶다면, subscribe를 이용하면 됨

 

import { createStore } from "redux";

const add = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");

number.innerText = 0;

const ADD = "ADD";
const MINUS = "MINUS";

const countModifier = (count = 0, action) => {
  switch (action.type) {
    case ADD:
      return count + 1;
    case MINUS:
      return count - 1;
    default:
      return count;
  }
};

const countStore = createStore(countModifier); // createStore은 우리에게 reducer를 주기를 요구함. reducer는 function이어야 함

const onChange = () => {
  number.innerText = countStore.getState();
};

countStore.subscribe(onChange);

const handleAdd = () => {
  countStore.dispatch({ type: ADD });
};
const handleMinus = () => {
  countStore.dispatch({ type: MINUS });
};

add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

if-else 대신 switch로 바꿈

-> Redux 공식 문서에서 자주 보임

string 대신 constant를 사용함

-> 오타가 났을 때 자바스크립트가 에러 잡아줌