Redux. 상태 관리

PpOee·2020년 3월 16일
0
post-thumbnail

Store 란?

우리의 data, 즉 state 값들을 저장하는 장소.

우선 store를 먼저 생성해보자.
store는 createStore를 통해 만들 수 있다.

import { createStore } from "redux";

를 한 뒤,

const reducer = () => {};

const store = createStore(reducer);

를 해주어 store를 만들어주었다.

참고로 createStore 인자로 안에 reducer 역할을 하는 함수가 들어가야한다.


Reducer 란?

data를 modify 해주는 함수.

reducer 함수가 리턴하는 값
우리 application의 data, state 값이 된다.

import { createStore } from "redux";

const countModifier = () => {
  return "Hello";
}

const countStore = createStore(countModifier);

console.log(countStore.getState());

예를 들어, 이 코드에서는 Hello 라는 문자열이 콘솔에 찍힌다.

countModifier 라는 data를 modify하는 리듀서가 "Hello" 를 리턴하기 때문에 우리 data 상태는 "Hello"가 되었기 때문이다.

리듀서에 초기값, 즉 initial state를 지정해보자.

import { createStore } from "redux";

const countModifier = (state  = 1) => {
  return state;
}

const countStore = createStore(countModifier);

console.log(countStore.getState());

콘솔에는 1이 찍힌다.
state 가 정해진 값이 없기 때문에 초기값으로 지정이 되기 때문이다.


Actions

import { createStore } from "redux";

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);

countStore.dispatch({ type: "add" });
countStore.dispatch({ type: "add" });
countStore.dispatch({ type: "add" });
countStore.dispatch({ type: "add" });
countStore.dispatch({ type: "minus" });
console.log(countStore.getState());

마지막 콘솔에는 어떤 숫자가 찍힐까?

우선, 여기서 data를 수정할 수 있는 function은 countModifier다.
( = Reducer )

따라서 우리는 밖에서 countModifier와 communicate할 수 있야하는데
countModifier와 communicate 할 수 있는 방법이 바로 countModifier에게 action을 보내는 것이다.
(참고로, action은 object 형태, 그리고 type을 가지고 있어야한다.)

밑에서 dispatch를 통해 countModifier에게 add, minus action들을 보내고 있는 것을 볼 수 있다.
따라서 count 값이 1 증가, 1 감소 되어 최종적으론 +4-1= 3 이 콘솔에 찍히는 것 !


Subscriptions

우리에게 store 안의 변화들을 알게 해주는 것.

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);

const handleAdd = () => {
  countStore.dispatch({ type: "add" });
}
const handleMinus = () => {
  countStore.dispatch({ type: "minus" });
}
add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

add 버튼을 클릭하면 countStore.dispatch({ type: "add" }); 가,
minuse 버튼을 클릭하면 countStore.dispatch({ type: "minus" }); 가 불리게 했다.

여기서 html의 number span 값을 count로 나타내고싶다면 어떻게 해야할까?

subscribe를 이용하여 state값이 바뀌는 시점을 캐치하여 그 순간에 number 값을 count 상태값으로 바꿔주면 될 것이다.

우선 변화가 생길 때마다 불릴 함수를 만들어야한다.

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

그리고 이 함수를 subscribe 인자 안에 넣어준다.

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);

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

const handleAdd = () => {
  countStore.dispatch({ type: "add" });
}
const handleMinus = () => {
  countStore.dispatch({ type: "minus" });
}
add.addEventListener("click", handleAdd);
minus.addEventListener("click", handleMinus);

그러면 이제 count 상태값이 바뀔 때 마다 onChangeState 함수가 불려 span 값이 업데이트된다.


reducer에 Switch를 활용하기

action type들이 여러개 이기 때문에 우리는 보통 switch문을 활용하여 리듀서 코드를 짠다.

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

countModifier를 switch문을 활용하여 바꾸어보았다.


총 정리 :

reducer가 data를 modify하는 함수이고, 이 reducer가 리턴하는 값이 data state 값이다.

그리고 이 reducer와 소통하기 위해서는 action을 보내야한다.

0개의 댓글