[React Native] MobX State Tree 학습하기 #2

in #zzan7 years ago (edited)

이전글 "[React Native] MobX State Tree 학습하기 #1" 에서 이어지는 내용입니다.


본 포스팅은 아래 강의를 보면서 정리한 노트입니다.




BookStore에 초기 데이터 등록하기

BookStore.js 파일을 수정합니다. books 배열에 다음과 같이 Book 정보를 입력합니다. 이제 BookStore는 book 데이터 하나를 가지고 생성됩니다.

const BookStore = types
  .model('Books', {
    books: types.array(Book),
  })
  .create({
    books: [
      // book 정보 등록
      {
        title: 'Ready Player One',
        author: 'Ernest Cline',
        read: true,
      },
    ],
  });


이제 앱을 실행하고 Console 에서 값을 확인해봅니다. Target의 첫번째 항목을 살펴보면, value에 우리가 입력한 Book 데이터가 보입니다.





BookStore에 addBook 액션(action) 추가하기

다시 BookStore.js 파일을 수정합니다. 그리고 actions에 addBook 함수를 추가합니다. actions에는 store에서만 호출할 수 있는 private 함수를 생성 할 수 있습니다. 이제 BookStoreaddBook 함수를 호출하면 books 배열에 새로운 book 객체가 추가됩니다.

const BookStore = types
  .model('Books', {
    books: types.array(Book),
  })
  // actions 추가
  .actions(self => ({
    addBook(book) {
      self.books.push(book);
    },
  }))
  .create({
    books: [
      {
        title: 'Ready Player One',
        author: 'Ernest Cline',
        read: true,
      },
    ], // 초기 값
  });




입력 화면 만들기

App.js 파일을 수정합니다. 그리고 react-native에서 StyleSheet, SafeAreaView, TextInput, Text, Button 컴포넌트를 import 합니다.

import {
  SafeAreaView,
  StyleSheet,
  TextInput,
  Text,
  Button
} from 'react-native';


그리고 initialState 값을 설정합니다. initialStatetitleauthor 속성을 가집니다.

const initialState = { title: '', author: '' };


그다음 state를 생성합니다. state의 기본값으로는 initialState 를 입력합니다. 그리고 onChangeText 함수와 addBook 함수를 생성합니다.

class App extends React.Component {

  state = initialState;

  // TextInput 입력 이벤트 함수
  onChangeText = (key, value) => {
    this.setState({
      [key]: value,
    });
  };

  // book 추가하기 함수
  addBook = () => {
    BookStore.addBook(this.state);
    this.setState(initialState);
  };

  ...


그 다음 화면 UI에 적용할 StyleSheet를 정의합니다. <TextInput> 컴포넌트의 높이는 50, 배경색은 회색 그리고 위아래 여백으로 10을 주었습니다.

const styles = StyleSheet.create({
  input: {
    height: 50,
    backgroundColor: '#ededed',
    marginVertical: 10,
  },
});


그리고 화면에 보여줄 입력 박스(TextInput) 2개와 버튼을 입력합니다. 첫번째 TextInput는 제목(title)를 입력받습니다. 두번째 TextInput는 저자(author)를 입력받습니다.

class App extends React.Component {
  ...
  render() {
    return (
      <SafeAreaView>
        <TextInput
          style={styles.input}
          value={this.state.title}
          onChangeText={value => this.onChangeText('title', value)}
        />
        <TextInput
          style={styles.input}
          value={this.state.author}
          onChangeText={value => this.onChangeText('author', value)}
        />
        <Button title="Add Book" onPress={this.addBook} />
      </SafeAreaView>
    );
};




MobX observer 클래스 등록하기

mobx-react에서 observerimport합니다. 그리고 대상 클래스 바로 위에 어노테이션 @observer를 입력합니다.

import { observer } from 'mobx-react';

@observer
class App extends React.Component {

...


그리고 다음은 지금까지 구현한 전체 소스코드입니다.

carbon.png


아래는 결과 화면입니다. 제목과 저자를 입력하고 Add Book를 누르면 아래에 추가된 정보가 표시됩니다.



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

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


vote, reblog, follow @anpigon


Sort:  

floridasnail님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
floridasnail님의 [나의 스팀엔진 이야기] 이번엔 주물주 위에 건물주, 건물주 위에 스엔주 (스팀 엔진 토큰과 그 임대풀) - Aug '19

... 한번 비교해보려고 합니다.지난 달에 스팀엔진에서는 토큰의 임대 내역을 알수 없다고 말씀드렸었는데요,
이제는 anpigon님이 만들어주신 https://happigon.github.io/#/wallet 에서 각 토큰의 임대 내역을 ...

Thank you for your continued support towards JJM. For each 1000 JJM you are holding, you can get an additional 1% of upvote. 10,000JJM would give you a 11% daily voting from the 700K SP virus707 account.

Congratulations @anpigon! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

You received more than 15000 upvotes. Your next target is to reach 20000 upvotes.

You can view your badges on your Steem Board and compare to others on the Steem Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

Vote for @Steemitboard as a witness to get one more award and increased upvotes!

kr-newbie님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
kr-newbie님의 [8/12 kr-newbie 큐레이팅 프로젝트]

...b.io/#/wallet/kr-newbie
happigon에서 자세한 임대내역이 확인 가능합니다.
만들어주신 anpigon께 감사드립니다!
anpigon님의 HAAPIGON 유저가이드를 참고해주시기 바랍니다!



<...

sct.notice님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
kr-newbie님의 [8/12 kr-newbie 큐레이팅 프로젝트]


    태그 작성 가이드라인 준수는 콘텐츠 관리와 글에 대한 접근성을 높이기 위해 반드시 필요한 절차입니다.
  • 스팀코인판에서 활용 가능한 태그는 크게 [보상태그 / 언어태그/ 주제태그]로 구분할 수 있습...

    wonsama.zzan님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
    wonsama.zzan님의 [ZZAN] DAILY REPORT 2019.08.12

    ...[댓글이벤트]감사&하루노트 - #00 12 anpigon/td> 22:25:48 [React Native] MobX 13

    wonsama님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^
    wonsama님의 이벤트) 제4회 제목학원 with 알라딘

    ...o8, floridasnail, ioioioioi, untold, kiwifi, goodhello, jjy, anpigon kibumh, asd5710, chosk
    맺음말
    • 많은 참여 바랍니다.

    Hi @anpigon!

    Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
    Your UA account score is currently 3.420 which ranks you at #7424 across all Steem accounts.
    Your rank has not changed in the last three days.

    In our last Algorithmic Curation Round, consisting of 157 contributions, your post is ranked at #77.

    Evaluation of your UA score:
    • You're on the right track, try to gather more followers.
    • The readers like your work!
    • You have already shown user engagement, try to improve it further.

    Feel free to join our @steem-ua Discord server