create account

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

View this thread on: hive.blogpeakd.comecency.com
· @anpigon · (edited)
$0.79
[React Native] MobX State Tree 학습하기 #2
https://img.youtube.com/vi/snBvYS6eC2E/mqdefault.jpg

이전글 [**"\[React Native\] MobX State Tree 학습하기 #1"**](/zzan/@anpigon/react-native-mobx-state-tree-1) 에서 이어지는 내용입니다.

___

본 포스팅은 아래 강의를 보면서 정리한 노트입니다.
https://www.youtube.com/watch?v=snBvYS6eC2E
___

<br><br>

# BookStore에 초기 데이터 등록하기

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

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

<br>

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

![](https://files.steempeak.com/file/steempeak/anpigon/BXbsbUny-1.png)

***

<br>
<br>

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

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

```js
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,
      },
    ], // 초기 값
  });
```

<br>
<br>

# 입력 화면 만들기

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

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

<br>그리고 `initialState` 값을 설정합니다. **initialState**는 `title`와 `author` 속성을 가집니다.

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

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

```js
class App extends React.Component {

  state = initialState;

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

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

  ...
```

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

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

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

```js
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>
    );
};
```

<br>
<br>

# MobX observer 클래스 등록하기

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

```js
import { observer } from 'mobx-react';

@observer
class App extends React.Component {

...
```

<br>

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

![carbon.png](https://files.steempeak.com/file/steempeak/anpigon/68pMhQTV-carbon.png)

<br>

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

|||
|-|-|
|![](https://steemitimages.com/740x0/https://files.steempeak.com/file/steempeak/anpigon/D6iI217Y-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-1120E1848BE185A9E18492E185AE206.53.13.png)|![](https://files.steempeak.com/file/steempeak/anpigon/EuSXwg0u-2019-08-112022-19-47.2019-08-112022_21_27.gif)|
***

<br>

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

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

***

<center><img src='https://steemitimages.com/400x0/https://cdn.steemitimages.com/DQmQmWhMN6zNrLmKJRKhvSScEgWZmpb8zCeE2Gray1krbv6/BC054B6E-6F73-46D0-88E4-C88EB8167037.jpeg'><h5>vote, reblog, follow <code><a href='/@anpigon'>@anpigon</a></code></h5></center>

<br>
👍  , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,
properties (23)
authoranpigon
permlinkreact-native-mobx-state-tree-2
categoryzzan
json_metadata{"app":"steemzzang/0.1","format":"markdown","tags":["zzan","kr-dev","liv","palnet","neoxian","sct","sct-freeboard","react-native","busy","jjm"],"links":["/zzan/@anpigon/react-native-mobx-state-tree-1","https://www.youtube.com/watch?v=snBvYS6eC2E","/@anpigon"],"image":["https://img.youtube.com/vi/snBvYS6eC2E/mqdefault.jpg","https://img.youtube.com/vi/snBvYS6eC2E/0.jpg","https://files.steempeak.com/file/steempeak/anpigon/BXbsbUny-1.png","https://files.steempeak.com/file/steempeak/anpigon/68pMhQTV-carbon.png","https://steemitimages.com/740x0/https://files.steempeak.com/file/steempeak/anpigon/D6iI217Y-E18489E185B3E1848FE185B3E18485E185B5E186ABE18489E185A3E186BA202019-08-1120E1848BE185A9E18492E185AE206.53.13.png","https://files.steempeak.com/file/steempeak/anpigon/EuSXwg0u-2019-08-112022-19-47.2019-08-112022_21_27.gif","https://steemitimages.com/400x0/https://cdn.steemitimages.com/DQmQmWhMN6zNrLmKJRKhvSScEgWZmpb8zCeE2Gray1krbv6/BC054B6E-6F73-46D0-88E4-C88EB8167037.jpeg"]}
created2019-08-12 13:25:48
last_update2019-08-28 22:34:09
depth0
children8
last_payout2019-08-19 13:25:48
cashout_time1969-12-31 23:59:59
total_payout_value0.617 HBD
curator_payout_value0.168 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length4,178
author_reputation17,258,940,000,931
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,438,930
net_rshares2,394,830,700,551
author_curate_reward""
vote details (49)
@steem-ua ·
#### 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](https://discord.gg/KpBNYGz)**
properties (22)
authorsteem-ua
permlinkre-react-native-mobx-state-tree-2-20190816t060006z
categoryzzan
json_metadata"{"app": "beem/0.20.23"}"
created2019-08-16 06:00:09
last_update2019-08-16 06:00:09
depth1
children0
last_payout2019-08-23 06:00:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length655
author_reputation23,214,230,978,060
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,585,625
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/kr-newbie/avatar) [kr-newbie](/@kr-newbie)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[kr-newbie](/@kr-newbie)님의 [[8/12 kr-newbie 큐레이팅 프로젝트]](/zzan/@kr-newbie/8-12-kr-newbie) <br /> 

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

<br>
<...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-native-mobx-state-tree-2-20190812t152809175z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-12 15:28:09
last_update2019-08-12 15:28:09
depth1
children0
last_payout2019-08-19 15:28:09
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length414
author_reputation7,218,006,883,278
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,443,411
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/sct.notice/avatar) [sct.notice](/@sct.notice)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[kr-newbie](/@kr-newbie)님의 [[8/12 kr-newbie 큐레이팅 프로젝트]](/zzan/@kr-newbie/8-12-kr-newbie#@sct.notice/re-kr-newbie-8-14521) <br /> 

 <blockquote><ul>
<i>태그 작성 가이드라인 준수는 콘텐츠 관리와 글에 대한 접근성을 높이기 위해 반드시 필요한 절차입니다. 
</li>
<li>스팀코인판에서 활용 가능한 태그는 크게 [보상태그 / 언어태그/ 주제태그]로 구분할 수 있습...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-native-mobx-state-tree-2-20190812t153033273z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-12 15:30:33
last_update2019-08-12 15:30:33
depth1
children0
last_payout2019-08-19 15:30:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length446
author_reputation7,218,006,883,278
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,443,508
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/wonsama.zzan/avatar) [wonsama.zzan](/@wonsama.zzan)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[wonsama.zzan](/@wonsama.zzan)님의 [[ZZAN] DAILY REPORT 2019.08.12](/zzan/@wonsama.zzan/zzan-daily-report-2019-08-12) <br /> 

 <blockquote>...<td>[댓글이벤트]감사&amp;하루노트 - #00</td>
<td>12</td>
</tr>
<tr>
<td>anpigon/td>
<td>22:25:48</td>
<td>[React Native] MobX </td>
<td>13</...</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-native-mobx-state-tree-2-20190812t154047872z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-12 15:40:48
last_update2019-08-12 15:40:48
depth1
children0
last_payout2019-08-19 15:40:48
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length450
author_reputation7,218,006,883,278
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,443,974
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/wonsama/avatar) [wonsama](/@wonsama)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[wonsama](/@wonsama)님의 [이벤트) 제4회 제목학원 with 알라딘](/zzan/@wonsama/4-with) <br /> 

 <blockquote>...o8, floridasnail, ioioioioi, untold, kiwifi, goodhello, jjy, anpigon kibumh, asd5710, chosk
맺음말<ul>
<li>많은 참여 바랍니다.</li>
</ul>
</blockquote>
properties (22)
authorsteem.apps
permlinkre---------react-native-mobx-state-tree-2-20190812t161151061z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-12 16:11:51
last_update2019-08-12 16:11:51
depth1
children0
last_payout2019-08-19 16:11:51
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length386
author_reputation7,218,006,883,278
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,444,994
net_rshares0
@steem.apps ·
![](https://steemitimages.com/32x32/https://steemitimages.com/u/floridasnail/avatar) [floridasnail](/@floridasnail)님이 anpigon님을 멘션하셨습니당. 아래 링크를 누르시면 연결되용~ ^^ <br />[floridasnail](/@floridasnail)님의 [[나의 스팀엔진 이야기] 이번엔 주물주 위에 건물주, 건물주 위에 스엔주 (스팀 엔진 토큰과 그 임대풀) - Aug '19](/zzan/@floridasnail/aug-19) <br /> 

 <blockquote>... 한번 비교해보려고 합니다.지난 달에 스팀엔진에서는 토큰의 임대 내역을 알수 없다고 말씀드렸었는데요,
이제는 anpigon님이 만들어주신 https://happigon.github.io/#/wallet 에서 각 토큰의 임대 내역을 ...</blockquote>
👍  
properties (23)
authorsteem.apps
permlinkre---------react-native-mobx-state-tree-2-20190813t220211997z
categoryzzan
json_metadata{"app":"steem.apps/0.1","format":"markdown"}
created2019-08-13 22:02:12
last_update2019-08-13 22:02:12
depth1
children0
last_payout2019-08-20 22:02:12
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length466
author_reputation7,218,006,883,278
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,493,260
net_rshares4,192,147,156
author_curate_reward""
vote details (1)
@steemitboard ·
Congratulations @anpigon! You have completed the following achievement on the Steem blockchain and have been rewarded with new badge(s) :

<table><tr><td><img src="https://steemitimages.com/60x70/http://steemitboard.com/@anpigon/voted.png?201908121350"></td><td>You received more than 15000 upvotes. Your next target is to reach 20000 upvotes.</td></tr>
</table>

<sub>_You can view [your badges on your Steem Board](https://steemitboard.com/@anpigon) and compare to others on the [Steem Ranking](https://steemitboard.com/ranking/index.php?name=anpigon)_</sub>
<sub>_If you no longer want to receive notifications, reply to this comment with the word_ `STOP`</sub>



###### [Vote for @Steemitboard as a witness](https://v2.steemconnect.com/sign/account-witness-vote?witness=steemitboard&approve=1) to get one more award and increased upvotes!
properties (22)
authorsteemitboard
permlinksteemitboard-notify-anpigon-20190812t151532000z
categoryzzan
json_metadata{"image":["https://steemitboard.com/img/notify.png"]}
created2019-08-12 15:15:33
last_update2019-08-12 15:15:33
depth1
children0
last_payout2019-08-19 15:15:33
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length843
author_reputation38,975,615,169,260
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,442,914
net_rshares0
@virus707 ·
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.
properties (22)
authorvirus707
permlinkre-react-native-mobx-state-tree-2-1565620352
categoryzzan
json_metadata{"tags":["jjm"]}
created2019-08-12 14:32:30
last_update2019-08-12 14:32:30
depth1
children0
last_payout2019-08-19 14:32:30
cashout_time1969-12-31 23:59:59
total_payout_value0.000 HBD
curator_payout_value0.000 HBD
pending_payout_value0.000 HBD
promoted0.000 HBD
body_length203
author_reputation557,563,606,581,756
root_title"[React Native] MobX State Tree 학습하기 #2"
beneficiaries[]
max_accepted_payout1,000,000.000 HBD
percent_hbd10,000
post_id89,441,186
net_rshares0