Redux 기본 사용법 (설치)

최하림·2022년 3월 3일
0

Redux 리덕스?

스토어(상점같은 판매자와 구매자 역활) 데이터를 모아두어 필요한 컴포넌트에서 데이터를 스토어에서 가져가서 사용하는 시스템.
중앙관리되는 데이터를 가져다 씀으로서, 데이터 누락, 무한화면그리기 없이 깔끔하다.
공식문서 링크

설치 방법

리액트프로젝트 시작단계

$ npx create-react-app [프로젝트명] --template redux

리액트 프로젝트를 이제 시작하려 한다면! CRA(create-react-app) 과 템플릿 지정으로 리덕스를 시작할 수 있다. react-redux 플젝 고고!
혹은 이미 프로젝트를 진행중이며, 리덕스를 추가하고자 한다면 아래 모듈을 설치하자!

redux

> $ npm i redux

만약 리덕스를 프로젝트에 추가하려 한다면 위 npm 명령어를 통해 리덕스를 추가하여 사용한다.

react-redux

$ npm i redux
$ npm i react-redux

리액트 프로젝트에 리덕스를 추가한다면 위 2개의 모듈 설치가 필요하다. react-redux, redux 를 설치하자!



import { createStore } from "redux"; 

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


// (리듀서/Reducer)
const countModifier = (count = 0) =>{

return count;

}

//           저장소/스토어
const countStore = createStore(countModifier);

console.log(countStore.getState())

✅ Store는 data를 저장하는 곳

✅ CreateStore는 reducer를 요구함.

✅ Reducer는 data를 modify 해주는 함수로 reducer가 return하는 것은 application에 있는 data가 됨.


action 과 dispatch 에 대한 설명

import { createStore } from "redux";

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


// (리듀서/Reducer)
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: "MINUS"});

console.log(countStore.getState())

✅ Action : redux에서 function을 부를 때 쓰는 두 번째 parameter 혹은 argument으로 reducer와 소통하기 위한 방법

✅ Reducer에게 Action을 보내는 방법 : store.dispatch({key: value})


subscribe 변화를 감지 하는 명령

import { createStore } from "redux";


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


// (리듀서/Reducer 데이터 수정하는곳)
const countModifier = (count = 0, action) =>{
                                    //액션이있어야 데이터를 받아온다 외부에서 
    if (action.type === "add"){
       return count + 1 
    } else if(action.type === "MINUS"){
        return count - 1
    } else{
        return count;
    }

    }

//           저장소/스토어(store)
const countStore = createStore(countModifier);


const handleAdd = () =>{
    countStore.dispatch({type:"add"})
}

add.addEventListener("click", handleAdd ) // 방법1
minus.addEventListener("click", () => countStore.dispatch({type:"MINUS"})) // 방법2


// 출력함
const onChange = () =>{
   number.innerText = countStore.getState()
}

     ///////변화를 감지 하고 출력해줄것을 보냄
countStore.subscribe(onChange)

✅ Subscribe : store 안에 있는 변화 감지
store.subscribe(func); // store안의 변화를 감지하면 func 실행


if 대신 switch 사용법

[코딩 완성본]

import { createStore } from "redux";


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

//오류 확인하게 좋기위해서
const ADD = "add";
const MINUS = "MINUS"

// (리듀서/Reducer 데이터 수정하는곳)
const countModifier = (count = 0, action) =>{

//if 대신 switch 사용법 좀더 보기좋다
    switch(action.type){
        case ADD:
            return(count + 1)
        case MINUS:
            return(count - 1)

        default:
            return count;
    }
    

    }

//           저장소/스토어
const countStore = createStore(countModifier);


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

add.addEventListener("click", handleAdd ) // 방법1
minus.addEventListener("click", () => countStore.dispatch({type:MINUS})) // 방법2


// 출력함
const onChange = () =>{
   number.innerText = countStore.getState()
}

            //변화를 감지 하고 출력해줄것을 보냄
countStore.subscribe(onChange)

총정리

✅ reducer : 현재 상태의 application과 함께 불려지는 function (+ with action)
return하는 것은 application의 state가 됨

✅ action : reducer와 소통하는 방법으로 Object여야 하며
그 key 이름은 항상 type임 (바꿀 수 없음)

✅ dispatch : reducer에게 action을 보내는 방법

✅ subscribe : store의 변화를 감지하면 인자값으로 준 함수를 실행

✅ switch가 자주 쓰임 [형식]

switch(action.type){
case ..blah..: 
return smth2

case ..blah2..:
return smth3

default: //디폴트값 기본값
return smth
}

✅ string으로 바로 쓰는 대신에 const variable로 선언해서 사용하기 => 에러 발견 용이하다

profile
노력하는 성장형

0개의 댓글