좌충우돌 개발자의 길

[Redux] 리덕스 기본 동작원리 본문

STUDYING/Redux

[Redux] 리덕스 기본 동작원리

sustronaut 2022. 12. 28. 17:48

출처 : 유데미 React 완벽 가이드

const redux = require('redux');

const counterReducer = (state={counter: 0}, action) => { // 리듀서 : 받아온 action으로 데이터 바꾸기 해줌 (현재상태, action)
    if (action.type === 'increment') {
        return {
            counter: state.counter + 1
        };
    }

    if (action.type === 'decrement') {
      return {
        counter: state.counter - 1,
      };
    }

    return state; // 다른 타입의 액션이면 현재상태인 state가 리턴됨
};

const store = redux.createStore(counterReducer); //store와 리듀서는 직접적으로 연결되어 있다

const counterSubscriber = () => {
    const latestState = store.getState(); // 변경된 데이터 스냅샷 가져오기
}

store.subscribe(counterSubscriber); // 구독 : 실행하는게 아님 가리키키만 하는거임

store.dispatch( { type: 'increment'}) // dispatch : 액션을 리듀서에 전달하기
store.dispatch({ type: 'decrement' }); // dispatch : 액션을 리듀서에 전달하기

'STUDYING > Redux' 카테고리의 다른 글

[Redux] 리덕스 기초  (0) 2022.06.19