Pure Redux : 01

gyomni·2022년 3월 5일
0

Redux

목록 보기
1/1
post-thumbnail

Redux

Javascript application들의 state(상태)를 관리하는 방법이다.

  • javascript의 application들이지 react의 application이 아니다!
  • reduxreact와 별개이다.
  • reduxangular, vue.js, (프레임워크 없는)vanilla.js 에서도 쓸 수 있다.
  • reduxreact에 의존하는 라이브러리가 아니다.

counter 예시로 알아보는 Vanilla - redux

Vanilla.js

vanilla javascript로 counter 만들기

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>Vanilla Redux</title>
  </head>
  <body>
    <button id="add">Add</button>
    <span></span>
    <button id="minus">Minus</button>  
  </body>
</html> 

index.js

const plus = document.getElementById("add");
const minus = document.getElementById("minus");
const number = document.querySelector("span");
let count = 0;

number.innerHTML=count;

// count를 더하고(handleAdd) 빼기만(handleMinus) 할 뿐, 값을 업데이트 하지 않음. number.innerHTML=count;는 한번만 일어나기 때문.
// ㄴ> updateText 있는 이유.
// html에 뭔가가 바뀌었다고 알려주기 위해 함수를 쓴다는 것 자체가 리덕스가 멋진것 중 하나이다.

const updateText =()=>{
  number.innerHTML=count;
}

const handleAdd=()=>{
  count+=1;
  updateText();
}

const handleMinus=()=>{
  count-=1;
  updateText();
}

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


이 application에서 data가 바뀌는 곳은! 유일하게 let count = 0; 이다.
-> count를 increse시키거나 decrese시키는 유일한 data


Vanilla Redux 🌝

위에서 vanilla javascript로 만든 counter 예시를 Redux로 만들어보자.

 redux 파헤치기 ⚓ 

📍 Redux를 사용
터미널에 yarn add redux 해준다.
( npm사용시에는 npm install redux 하기! )

📍 redux에서 createStore import하기

import { createStore } from "redux";
  • redux에는 createStore라는 함수가 있다.
  • Storedata / state 를 저장하는 곳.
    ( state는 application에서 바뀌는 data )
  • Store가 하는 일 : 기본적으로 data를 넣을 수 있는 장소를 생성한다.
    -> reduxdata를 관리하는데 도와주는 역할을 하기 위해 만들어 진 것!
    -> 현재 couter 예시에서 redux가 -1 or +1을 count하는 것을 도와주기 위해 만들어진 것!
    -> data를 어딘가에 넣어줘야 하고, 그 datastore이라는 곳에 저장(go on)되어야 한다.

📍 store 만들기

const store = createStore();

-> createStore에 마우스를 대보면, 아래와 같은 텍스트가 뜬다.

(alias) createStore<any, Action<any>, any, any>(reducer: Reducer<any, Action<any>>, enhancer?: StoreEnhancer<any, any>): any (+1 overload)
import createStore

-> createStore라는 함수는 reducer를 받기를 요구.

const reducer = () => {};

const store = createStore(reducer);

->reducer라는 함수를 만들어서 createStore에 넣어준다.
-> reducerdatamodify(수정)하는 것을 책임지는 함수로, reducerreturn하는 것은 application에 있는 data가 된다.
( ex) count를 increase or decrease )

📍 reducer or modifier는 ~!

1) data를 바꿔준다.
2) return하는 것은 application에 있는 data이다.

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

const countStore = createStore(countModifier);

console.log(countStore);


console.log(countStore.getState());

-> hello를 get하게 된다.


const countModifier = (state)=>{
  console.log(state)
  return state;
};

const countStore = createStore(countModifier);

-> countModifierinitial state로 불러 온다.
-> stateundefined 되었다.


const countModifier = (state = 0)=>{
  console.log(state)
  return state;
};

const countStore = createStore(countModifier);

-> defualt 더할 경우, state가 없다면, defualtstate0이 된다.
-> stateinitializing하는 것.


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

const countStore = createStore(countModifier);
console.log(countStore.getState())

-> get state하면state0과 같게 된다.

유일하게 countModifierdata / statemodify할 수 있다!
밖에 있는 다른 함수는 ❌❌❌
-> redux의 멋진 기능!
-> reduxdata가 기본적으로 한 곳에만 있다

countModifier++ or -- 를 어떻게 할까? -> action을 통해서 가능하다!


 count modify~ ! 🤠 

action 먼저 알고가자!

  • redux에서 function을 부를때 쓰는 두번째 parameter or argument이다.
  • reducer과 소통하기 위한 방법.
  • reducer에게 action을 보내는 방법 ↓↓
    						store.dispatch({key:value});

📍 state, action 출력

const countModifier = (count = 0, action)=>{
  console.log(count, action);
};

const countStore = createStore(countModifier);

-> 현재의 상태인 state가 있고, 만약에 이 존재하지 않는다면 0을 출력.
-> action은 현재 다소 난해한 것이 출력된다.

일단, countModifiercount+1 or count-1return하기 위해 action의 도움을 받아야 한다.

📍 countModifier가 2번 불렸다

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

const countStore = createStore(countModifier);
countStore.dispatch({type:"Hi~"});

-> 첫번째는 initialized된 function ( initialize with action ),
두번째는 type이라는 다른 action .

📍 dispatchcountModifier로 메세지 보내기

const countModifier = (count = 0, action) => {
  if(action.type ==="Add"){
    console.log("they are telling me to add one 🤟 ")
  }
  return count;
};

const countStore = createStore(countModifier);
countStore.dispatch({type:"Add"});

-> 전송한 메세지는 action에 넣고, action체크하기

📍 counter 기능 구현

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"});		// 1
countStore.dispatch({type:"Add"});		// 2
countStore.dispatch({type:"Add"});		// 3
countStore.dispatch({type:"Add"});		// 4
countStore.dispatch({type:"Add"});		// 5
countStore.dispatch({type:"Add"});		// 6
countStore.dispatch({type:"Add"});		// 7
countStore.dispatch({type:"Minus"});	// 6

console.log(countStore.getState());

  • count가 증가되는 이유
    -> countreturn하면, count는 0이다.
    -> 그리고 countStore.dispatch()를 말하면 if문 조건에 맞을 대 count+1을 return해준다. 즉 count는 1
    -> return된 것은 현재의 state가 된다.
    -> 다시 dispatch를 부른다.

📍 state상태 보기

const countModifier = (count = 0, action) => {
  console.log(count, 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:"Add"});
countStore.dispatch({type:"Add"});
countStore.dispatch({type:"Add"});
countStore.dispatch({type:"Minus"});
console.log(countStore.getState());

-> state변화를 볼 수 있다.

 정리 💨  
  • datamodify 할 수 있는 functioncountModifier이다.

  • 밖에서 countModifier와 커뮤니케이션 할 수 있어야 하고, 그 방법은
    countModifier에게 action을 보내는 것이다.

    이제 dispatch와 모든 것들을 button에 연결하고 마무리하자!!


Subscriptions 🌝

: store안의 변화를 감지한다.

📍 button에 이벤트 연결해주기

import { createStore } from "redux";

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

const countModifier = (count = 0, action) => {
  console.log(count, action)
  if(action.type ==="Add"){
    return count + 1;
  }else if(action.type ==="Minus"){
    return count - 1;
  }else{
    return count;
  }
};

const countStore = createStore(countModifier);

plus.addEventListener("click", ()=> countStore.dispatch({type:"Add"})); // 익명함수 사용해야 한다. or 함수 빼서 선언해주기.
minus.addEventListener("click", ()=> countStore.dispatch({type:"Minus"}));

-> 버튼을 클릭하면 이벤트가 잘 실행된다.
-> But, 현재 html은 notified되지 않았다.


countStore를 콘솔에서 다시 보면,

console.log(countStore);

-> 사용하고 있는 dispatch, getState가 보이고 Subscriptions가 보인다! (replaceReducer은 무시하기!)
-> Subscriptionsstore안에 있는 변화들을 알 수 있게 해준다.

📍 storesubscribe하기

const onChange = () =>{
  console.log("there was change on the store");
}
countStore.subscribe(onChange);

-> 버튼을 클릭하면 store에 변화가 생긴다.

📍 UI로 보여주기~!

import { createStore } from "redux";

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

number.innerHTML= 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);

// onChange함수는 store에 변화가 있을때마다 감지해서 불려진다.
const onChange = () =>{
  number.innerHTML =countStore.getState();
}
countStore.subscribe(onChange);

plus.addEventListener("click", ()=> countStore.dispatch({type:"Add"})); // 익명함수 사용해야 한다. or 함수 빼서 선언해주기.
minus.addEventListener("click", ()=> countStore.dispatch({type:"Minus"}));


data를 수정하는 유일한 곳은 reducer안 ( = countModifier )이다 ! 😝👍

학습 : 초보자를 위한 리덕스 101

profile
Front-end developer 👩‍💻✍

0개의 댓글