Redux - 개념정리(비유 및 코드)


이제 장난감 가게가 아래의 사진과 같이 있다고 하겠습니다.



initialState : 'Alex 장난감 판매점'에서 10개의 장난감을 팔려고 합니다.

reducer : 가게에는 1명의 직원이 장난감을 팔고 있습니다.

action.type : 고객이 장난감을 달라고 요청합니다.

dispatch : 직원이 응답을 합니다.

storage : Alex 장난감 판매점의 가게




이제 직원이 고객한테 장난감을 주면(action) 선반의 장난감은 -1이 됩니다. 위 그림과 내용을 기억하면서 아래 코드를 확인해 주시기 바랍니다.





 Action 

1. 유일하게 storage와 상호작용할수 있는 방법이다.

2. redux storage에 정보를 전달할수 있다.

3. JavaScript 객체이다.

4. 키로 'type'가 존재하며 value값에 의해 action의 행동이 정해진다

5. 'type'의 value값의 속성은 보통 문자열이다.


const BUY_TOY = 'BUY_TOY'; // type을 설정한다(문자열)

function buyToy(){
return {
type: BUY_TOY,
info: 'First step of redux action'
}
}


Reducer

(이전 state, action) => 새로운 state


// Reducer
// (previousState, action) => newState

// 초기 state상태
const initialState = {
numOfToy: 10 // 초기에 장난감이 10개
}

const reducer = (state = initialState, action) => {
switch(action.type){ // action의 타입을 확인하여 case를 실행
case BUY_TOY: return { // 장난감을 구매하는 action
...state, // 이전 단계의 state를 복사한다.
numOfToy : state.numOfToy -1 // numOfToy만 이전 state에서 1 감소
};

default : return state; // 어느 case에도 속하지 않으면 그대로 state 출력
}
}


Storage : 전체 app에서 하나의 Storage만 존재한다.

1. app의 state를 갖고 있는다.

2. method getState()를 통해서 state에 접근할수 있도록 한다.

3. method dispatch(action)를 통해서 state를 updated할수 있도록 한다.

4. method subscribe(listener)를 통해 listeners를 등록한다. (state가 변경시 app에 반영)

5. 등록되지 않은 listeners 해제


Storage를 설정하기 전에 require가 있다.

const redux = require('redux')
const createStore = redux.createStore;

위 2줄의 코드를 추가한다.


// 1. app의 state를 갖고 있는다. (인자로 reducer)
// createStore를 이용하여 storage를 생성
const storage = createStore(reducer);

// 2. method getState()를 통해서 state에 접근할수 있도록 한다.
console.log('초기상태', storage.getState());

// 4. method subscribe(listener)를 통해 listeners를 등록한다. (state가 변경시 app에 반영)
// state가 업데이트 될때마다 console.log에의해 업데이트 상태 storage.getState()에 의해 출력된다.
const unsubscribe = storage.subscribe(() => console.log('업데이트 상태', storage.getState()));


// 3. method dispatch(action)를 통해서 state를 updated할수 있도록 한다.
// dispatch을 통해 action을 취할때 reducer는 action.type가 BUY_TOY라는 것을 알수 있습니다.
storage.dispatch(buyToy());
storage.dispatch(buyToy());
storage.dispatch(buyToy());

// 5. 등록되지 않은 listeners 해제
unsubscribe();

storage.dispatch(buyToy()); // 실행이 안됨



위와 같은 상태로 콘솔로그에 찍히는 것을 알수 있다.


 

이전글 : Redux - 개념


다음글 : Redux - 여러개의 state


위 자료 관련 코드(아래)


const redux = require('redux')
const createStore = redux.createStore;


// Action
const BUY_TOY = 'BUY_TOY'; // type을 설정한다(문자열)
function buyToy(){
return {
type: BUY_TOY,
info: 'First step of redux action'
}
}


// Reducer
// (previousState, action) => newState

// 초기 state상태
const initialState = {
numOfToy: 10 // 초기에 장난감이 10개
}

const reducer = (state = initialState, action) => {
switch(action.type){ // action의 타입을 확인하여 case를 실행
case BUY_TOY: return { // 장난감을 구매하는 action
...state, // 이전 단계의 state를 복사한다.
numOfToy : state.numOfToy -1 // numOfToy만 이전 state에서 1 감소
};

default : return state; // 어느 case에도 속하지 않으면 그대로 state 출력
}
}

// 1. app의 state를 갖고 있는다. (인자로 reducer)
// createStore를 이용하여 storage를 생성
const storage = createStore(reducer);

// 2. method getState()를 통해서 state에 접근할수 있도록 한다.
console.log('초기상태', storage.getState());

// 4. method subscribe(listener)를 통해 listeners를 등록한다. (state가 변경시 app에 반영)
// state가 업데이트 될때마다 console.log에의해 업데이트 상태 storage.getState()에 의해 출력된다.
const unsubscribe = storage.subscribe(() => console.log('업데이트 상태', storage.getState()));


// 3. method dispatch(action)를 통해서 state를 updated할수 있도록 한다.
// dispatch을 통해 action을 취할때 reducer는 action.type가 BUY_TOY라는 것을 알수 있습니다.
storage.dispatch(buyToy());
storage.dispatch(buyToy());
storage.dispatch(buyToy());

// 5. 등록되지 않은 listeners 해제
unsubscribe();

storage.dispatch(buyToy()); // 실행이 안됨






댓글

이 블로그의 인기 게시물

Lesson 12_1 프로퍼티 노드(Property Node)

DAQ로 전압 측정하기-2

Lesson 12_2 참조를 이용한 프로퍼티노드(Property Node)