[React] Mobx-state-tree 학습하기 #1 : Mobx-state-tree를 사용해서 Reat State 관리하기

anpigon(63)
Published in
#zzan
Words
262
Reading
2 min
Listen
Play
7y

안녕하세요. 안피곤입니다.

저는 최근에 mobx-state-tree를 열심히 공부하고 있습니다. 제이콥님이 알려주신 Mobx는 너무 매력적입니다. 그래서 학습 중이던 Redux, Redux-Thunk, Redux-Saga를 그만두고, Mobx 동영상 강의를 찾아서 열심히 배우고 있습니다. 개발자에게 기술 공부는 끝이 없습니다. 기술 트렌드는 매년 바뀝니다. 그리고 유투브에는 새로운 무료 강의가 계속 업로드되고 있습니다.

저는 작년부터 Front-End, Node.js, React 세계에 발 담그면서 새로운 기술을 계속 공부하고 있습니다. 매일매일 새로운 기술이 쏟아져 나오고 있고, 새로운 기술들은 또 저에게 신선함을 안겨줍니다. 새로운 기술을 처음 배울때는 어렵지만, 이 기술에 익숙해지고 나면 그 다음 개발할 때는 매우 편합니다.








이 레슨은 위시리스트 앱을 만드는 과정을 안내합니다. 그리고 우리는 mobx-state-tree(MST)의 핵심 모델을 살펴볼 것입니다. 모델(Model)은 상태(state)의 형태(shape)을 정의하고 타입 유효성 검사를 수행합니다.

우리는 다음을 배우게 됩니다.

  • types.Model를 사용하여 모델을 정의하기
  • Model.create를 사용하여 JSON에서 모델 인스턴스화하기
  • Primitive types : types.stringtypes.number
  • Type inference for primitive types
  • types.array
  • types.optional
  • Composing models into a model tree

mobx-state-tree(MST) Models를 사용하여 어플리케이션 도메인 정의하기

wishlist 프로젝트 생성하기

우선 React App 프로젝트를 생성합니다.

$ npx create-react-app wishlist

(npx는 npm 5.2+ 이상 부터 사용가능합니다. 이전 버전을 사용중이라면 "instructions for older npm versions" 문서를 참고하세요.)


아래와 같이 필요한 모듈이 설치되면서 프로젝트가 생성됩니다.

create-react-app wishlist

Mobx 모듈 설치하기

다음 명령어를 입력하여 mobx와 mobx-state-tree 모듈을 설치합니다.

$ yarn add mobx mobx-react mobx-state-tree


아래 화면처럼 설치가 진행됩니다.

model 생성하기

./src 폴더 아래에 model 폴더를 생성합니다.


그리고 WhishList.js 파일을 생성합니다.


WhishList.js 파일에는 다음 내용을 입력합니다.

// src/models/WhishList.js

import { types } from "mobx-state-tree";

// WishListItem 모델 정의
export const WishListItem = types.model({
    name: types.string,
    price: types.number,
    image: types.optional(types.string, ""),
});

// WishList 모델 정의
export const WishList = types.model({
  items: types.optional(types.array(WishListItem), [])
});


WishListItemimage 속성은 optional이며 기본값은 ""입니다. 그리고 image를 아래와 같이 입력할 수도 있습니다.

export const WishListItem = types.model({
    // ...
    image: ""
});




WhishList 모델 테스트 하기

WhishList.test.js 파일을 생성합니다.


WhishList.test.js 파일에는 다음 내용을 입력합니다.

import { WishListItem, WishList } from "./WhishList";

it("can create a instance of a model", () => {
  const item = WishListItem.create({
    name: "Reat Native - anpigon",
    price: 28.73
  });

  expect(item.price).toBe(28.73);
  expect(item.image).toBe("");
});

it("can create a wishlist", () => {
  const list = WishList.create({
    items: [
      {
        name: "Reat Native - anpigon",
        price: 28.73
      }
    ]
    });
    
    expect(list.items.length).toBe(1);
    expect(list.items[0].price).toBe(28.73);
});



테스트 하기 위해서 yarn test를 입력합니다.

yarn test

테스트에 성공하면 다음과 같은 메세지가 콘솔에 출력됩니다.
테스트 성공




댓글, 팔로우, 좋아요 해 주시는 모든 분께 감사합니다.

항상 행복한 하루 보내시길 바랍니다.


vote, reblog, follow @anpigon


Originally posted on 안피곤님의 블로그. Steem blog powered by ENGRAVE.