출처: https://academy.nomadcoders.co/courses/enrolled/235420

Nomade coder redux 강의

(Pure redux : counter 만들기)

1.1 Store? where you store(=put) your data

    const countModifier = (state = 0) => {   // 나의 데이터를 modify 하는 함수(=reducer). return 하는 값이 내 데이터다 (?)  
        console.log(state);                     //state = 0 로 초기값 지정
        return state;
    }
    const countStore = createStore(countModifier);  //데이터를 담을 곳

Reducer

리듀서 함수(여기선=countModifier)는 이전 상태와, 액션 객체를 파라미터로 받는다. 이전의 상태는 절대로 건드리지 않고(Do NOT MUTATE EVER), 변화를 일으킨 새로운 상태 객체를 만들어서 반환한다. 똑같은 파라미터로 호출된 리듀서 함수는 언제나 똑같은 결과값을 반환해야만 한다.

Store

Store(스토어) Store는 앱의 전체 상태를 저장하고있는 창고

    const countModifier = (count = 0, action) => {   // 나의 데이터를 modify 하는 함수. return 하는 값이 내 데이터다 (?)  => 리듀서 라고 부름
        console.log(count, action);
        if(action.type === "ADD"){
            console.log("do Add");
        }
        return count;
    }
    const countStore = createStore(countModifier);  //데이터를 담을 곳

    countStore.dispatch({type: "ADD"});  //JSON 형식으로 들어가야함

Reducer들은 각각의 상태변화를 어떻게 시킬지 관리해주는 정보가 담겨져 있다.이들은 전부 Store와 정보를 주고받는 역할을 한다.

Reducer는 그안에서 애플리케이션에 어떤 변화가 생긴다면 전달된 Action을 보고 어떻게 state를 교체시킬지 관리해주는 역할을한다.

버튼에 액션 추가하기

    import {createStore} from "redux";

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

    const countModifier = (count = 0, action) => {   // 나의 데이터를 modify 하는 함수. return 하는 값이 내 데이터다 (?)  => 리듀서 라고 부름
        if(action.type === "ADD"){
            return count + 1;
        } else if (action.type === "MINUS"){
            return count - 1;
        }else{
            return count;
        }

    }
    const countStore = createStore(countModifier);  //데이터를 담을 곳

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

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

action

Action은 Store라는 저장소에 정보를 전달하기 위한 데이터 묶음이다. reduce함수로 state를 변경하려고 할 때 사용! 액션을 어떻게 사용하느냐? dispatch() 에 넣어서

getState & dispatch

getState

getState는 store안의 상태를 가져와준다.

// Store의 상태를 확인하기 위해 console에 찍어본다. console.log(store.getState());

dispatch(action)

스토어에 있는 reducer들에게 action을 전달해준다. 각각의 reducer들은 자신에게 맞는 action이 들어온다면 store의 상태를 교체 할것이다.

subscribe

    state 받아보는 
    const onChange = function() {
        number.innerText = countStore.getState();
    };

    countStore.subscribe(onChange);   //state 변화를 감지하는 함수 = subscribe