React-Redux_기초2 Redux 폴더 코딩

 이제 React안에 Redux를 사용할수 있도록 코딩하도록 하겠습니다. 



위 사진과 같이 Redux폴더 안에 toy라는 폴더를 생성하고 3개의 파일을 만듭니다. 이전에 작성한 글처럼 toy에 관련된 Types, Action, Reducer를 이용합니다.

export const BUY_TOY = "BUY_TOY"; // 장난감을 사기위한 타입 입력
export const SELL_TOY = "SELL_TOY"; // 장난감을 팔기위한 타입 입력

toyTypes.js은 BUY_TOY, SELL_TOY에 문자열을 변수로 입력하고 export합니다.


import {BUY_TOY, SELL_TOY} from './toyTypes';

// 장난감을 사기위한 액션
export const buyToy = () => {
return {
type : BUY_TOY
};
};

// 장난감을 팔기위한 액션
export const sellToy = () => {
return {
type : SELL_TOY
};
};

toyAction.js에는 toyTypes.js에서 BUY_TOY, SELL_TOY를  import해서 액션에 사용합니다. 액션은 2가지 buyToy, sellToy로 이루어 집니다. 


import { BUY_TOY, SELL_TOY } from './toyTypes'; // toyTypes에서 구매와 판매 타입을 받아온다.

const initialState = {
numOfToys : 20 // 초기 장난감 진열 갯수는 20개
};

const toyReducer = (state = initialState, action) => {
switch(action.type){
case BUY_TOY: // 가게에서 장난감을 사기 때문에 -1한다

return {
...state,
numOfToys : state.numOfToys - 1
}
case SELL_TOY: // 가게에서 장난감을 사기 때문에 +1한다
return {
...state,
numOfToys : state.numOfToys + 1
}

default : return state // 해당 타입이 아니면 그대로 state를 return 한다.
}
}

export default toyReducer;


toyReducer.js 에서는 Reducer를 switch문을 이용하여 만듭니다. 구매, 판매 케이스를 생성하고 이외에도 해당되지 않는 action에 대해서는 default처리를 합니다. 


이제 toy폴더에 대한 코딩은 완료가 되었습니다. 이제 toy폴더의 상위단인 Redux폴더에 .js파일을 추가하도록 하겠습니다.



이제 Redux폴더안에 3개의 js파일을(index.js, rootReducer.js, store.js) 생성합니다.


// buyToy, sellToy의 action을 export한다.
export { buyToy, sellToy } from './toy/toyAction';

먼저 index.js파일에서 buyToy, sellToy의 액션을 export한다. 


// toyReducer를 import한다.
import toyReducer from './toy/toyReducer';

// 나중에 rootReducer에 다른 reducer를 병합하기 위해
// 변수를 선언한다. 지금 예제에서는 reducer가 하나이기 때문에
// toyReducer만 입력한다.
const rootReducer = toyReducer;

// rootReducer를 export한다.
export default rootReducer;

 이제 rootReducer.js에서 toyReducer를 import후 rootReducer에 입력한다. 향후 예제에서 rootReducer에 다른 reducer를 추가하는 방법에 대해서 설명 하겠습니다.


import { createStore } from 'redux'; // store를 만들기 위해 import
import rootReducer from './rootReducer'; // reducer에서 store를 사용하기 위해 import

const store = createStore(rootReducer); // store생성

export default store;

마지막으로 store를 생성합니다. store.js에서 createStore를 이용해 store를 생성합니다. 이때 rootReducer를 사용하여 store를 생성하고 export합니다.


위 코드를 작성하시면 Redux폴더에 대한 모든 코드는 완료가 된 것입니다. 이제 다음에는 components와 App.js를 코딩하여 장난감 가게에 있는 상품을 Redux로 관리할수 있게 하겠습니다.



이전글 : React-Redux_기초1 React생성,  Redux 폴더 생성, dependencies설치

다음글 : React-Redux_기초3 components폴더 및 App.js 코딩





댓글

이 블로그의 인기 게시물

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

DAQ로 전압 측정하기-2

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