티스토리 뷰

Redux

Redux 사용법 !

범블루 2022. 2. 25. 19:58

Redux 없는 Vanila JS로 간단한 코드를 살펴보겠습니다.

 

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

let count = 0;
number.innerText = count;

const updateText = ()=>{
  number.innerText = count;
}
const handleAdd = () => {
  count++;
  updateText();
};
const handleMinus = () => {
  count = count - 1;
  updateText();
};

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

화면에는 이렇게 버튼 2개와 span 태그로 이루어져 있습니다.

우리는 버튼을 누를 경우 span 태그에 값이 바뀌게  됩니다. 아무 문제는 없지만 

Redux를 함께 사용하면 코드의 변화가 어떻게 이루어지는데 보겠습니다.

 

저는 vs code를 이용하며, nodejs를 설치 후 터미널에 명령을 적습니다.

 

1) npm install redux  // yarn을 사용하는 경우 yarn add redux

2) js 파일 상단에 import {createStore} form "redux"; 

 

설치와 import를 끝냈습니다.

 

우선 Store는 data를 넣는 곳이며, state라고 부릅니다

State는 application에서 바뀌는 data를 의미하는 것을 알아야 합니다.

 

리덕스에는 createStore라는 function (함수) 가있고,

store 가 하는 일은 기본적으로 data를 넣을 수 있는 장소를 생성합니다.

리덕스는 data를 관리하는데 도움을 주기 위해 만들어졌습니다.

 

버튼을 눌렀을 때  count 값이 +1 이 되거나 -1 이 되게 도와주는 것입니다. 

 

일단 1) data를 넣어줘야 하고 , 2)  data를  store에 저장해야 합니다. 3) store 에는 reducer라는 함수가 필요합니다.!

 

reducer는 함수이며 data를 modify (수정) 해주죠!

 

const reducer = ()=>{};
const store = createStore(reducer)
 
 console.log(countStore); 를 해보면 개발자도구에 consol 창을 보면
 
오브젝트 형식의 자료를 볼수있습니다.
 
{dispatch: ƒ, subscribe: ƒ, getState: ƒ, replaceReducer: ƒ, @@observable: ƒ}
 
const reducer = ()=>{
  return 'hello';
};


const countStore = createStore(reducer)

console.log(countStore.getState());

console.log(countStore.getState()); 해보면 

 

hello라는 값을 얻을 수 있습니다 countStore에 state에는 reducer 가 return 한 값이 들어있다는 것을 확인할 수 있습니다.

 

위에서 말했듯이 reducer는 data를 수정할 수 있는데, data는 유일하게 reducer를 통해서만 수정할 수 있습니다.

 

수정을 하기 위해 선 action을 사용해야 합니다.

 

action 은 redux에서 function을 부를 때 사용하는 두 번째 parameter , 혹은 argument입니다.

 

action 은 reducer와 소통할 수 있는 유일한 방법!

 
const reducer = (count = 0, action) => {
 
  if (action.type === "add") {
    return count+2;
  } else if (action.type === "minus") {
    return count-1;
  } else{
    return count;
  }
 
};

 

// switch 문을 사용해도 된다.
const reducer = (count = 0, action) => {
  switch (action.type) {
    case "ADD":
      return count + 1;
    case "MINUS":
      return count - 1;
    default:
      return count;
 
  }
};

const countStore = createStore(reducer);

countStore.dispatch({ type: "add" });

console.log(countStore.getState());   // = 2

countStore.dispatch({ type: "minus" });

console.log(countStore.getState());   // = 1
 
 
 
위에코드는 reducer함수 내부에 if 조건문을 통해 action.type 으로 조건을 확인하고 조건에 맞는 명령을 실행하여
 
 return 하면 return 된값이 state 가 되는데 count 가 state라고 생각하면 됩니다.
 
2개의 parameter 중 ( state , action ) 인데 count 로 이름을 바꾼것 뿐입니다 (state로 사용해도 됩니다)
 
reducer 에 요청을 할때는 countStore.dispatch({type: " 작명 " })  사용하면 됩니다.
 
 
정리해 보면
 
reducer 는 값을 수정하는데 수정할수있는 방법은
action.type 을 통해서만 접근(수정) 할수 있으며  action.type에 접근할때는 
createStore 로 생성한 countStore 에 .dispatch 를 붙여서dispatch 에 type 을지정해주고
그 type 값이 다시 reducer 에 조건문에서 action.type 이 일치한곳에서 실행이되고 return 되서 state에 저장되게됩니다.
이상 redux 사용방법 이였습니다.
 
 

*잘못된 부분이 있다면 댓글 부탁드리겠습니다*