Notice
Recent Posts
Recent Comments
Link
«   2025/02   »
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28
Tags
more
Archives
Today
Total
관리 메뉴

바스키아

Mobx Document 둘러보기 본문

JS/Mobx

Mobx Document 둘러보기

바스키아1 2019. 8. 21. 17:05

이제 한 4개월차 넘은것같다. 머리가 빠꾸라 실력은 제자리

하지만 느낀게 몇개 있는데 그중 하나가 해당 라이브러리가 제공하는 Document를 잘봐야한다는 것이다.

질문방, 블로그예제글 도움많이 받지만 기본문서 자세히보는게 제일 중요한듯하다.

 

Mobx document 정보 : https://mobx.js.org

깃허브에 기재된 Mobx 정보 : https://github.com/mobxjs/mobx

 

깃허브쪽을 먼저 둘러보자

처음부터 스폰 많이 받는다고 자랑질이다....ㅋㅋ

그밑으론 Mobx 버전에 따른 es버전의 브라우저 지원에 관한 내용들이 나열되있다.( 보고 판단하여 맞는 버전을 받자 )

 

중국만 번역해주냐 하지말자.... 리액트 자체가 중국것이다..ㅋㅋㅋㅋㅋ

 

Introduction 부분에 핵심적인 문장은 이것이다.

Anything that can be derived from the application state, should be derived. Automatically.

application의 state를 어디로든 자동으로 전달할수 있다는 말이다. 부모컴포넌트로 일일이 꾸역꾸역 안넣어도 된다 이말이다. --> state 저장소 

 

React는 렌더링 가능한 컴포넌트 트리로 변환하는 메커니즘을 제공하여 애플리케이션 상태를 렌더링합니다.

MobX는 React가 사용한 애플리케이션 상태를 저장하고 업데이트하는 메커니즘을 제공합니다.

okky? -->리액트 특징인 리렌더링시 전체를 로드하는게 아니고 바뀐 부분만 교체해주는 (전체를 인지한 상태에서)

부분을 Mobx가 이에 상태를 저장하고 업데이트하는 방법을 취하고 있단 말이다. (설명이 구려서 그렇지만 이해가 안간다면 Virtual DOM 개념을 다시보고 오셔야 할것입니다).

나머진 본인기술자랑~

 

The following snippets can be tried online using codesandbox example.  -->https://codesandbox.io/s/v3v0my2370

**스니펫(snippet)은 재사용 가능한 소스 코드, 기계어, 텍스트의 작은 부분을 일컫는 프로그래밍 용어이다.(몰랐어ㅜㅜ)

 

이후 이제 본격적인 우리가 공부해야할 내용이 나온다.

CORE CONCEPT (핵심 컨셉)

 

 

1.Observable state

MobX adds observable capabilities to existing data structures like objects, arrays and class instances

-->데이터 구조를 관찰 가능한 상태로 만들어준다.... 즉 @observable 태그를 붙여주면 state를 주시하는 상태가 된다.(state값이 바뀌면 변경되게끔!!)

 

1
2
3
4
5
6
7
import { observable } from "mobx"
 
class Todo {
    id = Math.random()
    @observable title = ""
    @observable finished = false
}
 

 

If your environment doesn't support decorator syntax, don't worry. You can read here about how to set them up. Or you can skip them altoghether, as MobX can be used fine without decorator syntax, by leveraging the decorate utility. Many MobX users prefer the slightly more concise decorator syntax, but the following snippet achieves the same:

-->문법환경때문에 안되면 위에 링크타고 해법을 찾아야 됩니다. 그리고 다음 스니펫도 동일합니다.

1
2
3
4
5
6
7
8
9
10
11
import { decorate, observable } from "mobx"
 
class Todo {
    id = Math.random()
    title = ""
    finished = false
}
decorate(Todo, {
    title: observable,
    finished: observable
})
 

왠만하면 깔끔하게 @observable 쓰는게 편하지 ㅎㅎ

 

 

2.Computed values

 

With MobX you can define values that will be derived automatically when relevant data is modified. By using the @computeddecorator or by using getter / setter functions when using ㅇ\(extend)Observable (Of course, you can use decorate here again as alternative to the @ syntax).

 

-->@computed 를 getter의 역할로 사용한다는 것!!

1
2
3
4
5
6
7
class TodoList {
    @observable todos = []
    @computed
    get unfinishedTodoCount() {
        return this.todos.filter(todo => !todo.finished).length
    }
}
 

 

MobX will ensure that unfinishedTodoCount is updated automatically when a todo is added or when one of the finishedproperties is modified. Computations like these resemble formulas in spreadsheet programs like MS Excel. They update automatically and only when required.

-->finished속성 중 하나 가 수정 될 때 자동으로 업데이트 되도록합니다.

(엑셀, 스프레드시트 이런거에 계속 비유하는데 나 이거 모른다고;;)

 

3.Reactions

Reactions are similar to a computed value, but instead of producing a new value, a reaction produces a side effect for things like printing to the console, making network requests, incrementally updating the React component tree to patch the DOM, etc. In short, reactions bridge reactive and imperative programming.

-->쉽게 말하면 reactiv 와 imperative중 반응형 프로그래밍을 한다는 것이다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import React, { Component } from "react"
import ReactDOM from "react-dom"
import { observer } from "mobx-react"
 
@observer
class TodoListView extends Component {
    render() {
        return (
            <div>
                <ul>
                    {this.props.todoList.todos.map(todo => (
                        <TodoView todo={todo} key={todo.id} />
                    ))}
                </ul>
                Tasks left: {this.props.todoList.unfinishedTodoCount}
            </div>
        )
    }
}
 
const TodoView = observer(({ todo }) => (
    <li>
        <input
            type="checkbox"
            checked={todo.finished}
            onClick={() => (todo.finished = !todo.finished)}
        />
        {todo.title}
    </li>
))
 
const store = new TodoList()
ReactDOM.render(<TodoListView todoList={store} />document.getElementById("mount"))
cs

If you are using React, you can turn your (stateless function) components into reactive components by simply adding the observer function / decorator from the mobx-react package onto them.

->@observer  반응형 프로그래밍을 하기위한 어노테이션이다 위에 코드는 TodoListView class를 반응형으로 사용하겠다는 의미다. 그리고 이 어노테이션을 쓰기위해서 mobx-react 패키지를 물러와야 한다는 말.

 

 

observer turns React (function) components into derivations of the data they render. When using MobX there are no smart or dumb components. All components render smartly but are defined in a dumb manner. MobX will simply make sure the components are always re-rendered whenever needed, but also no more than that. So the onClick handler in the above example will force the proper TodoView to render, and it will cause the TodoListView to render if the number of unfinished tasks has changed. However, if you would remove the Tasks left line (or put it into a separate component), the TodoListView will no longer re-render when ticking a box. You can verify this yourself by changing the JSFiddle.

--> 결국엔 virtual DOM 장점처럼 변동부분만 반응형으로 처리되고 변동이 안되었다면 그이상 처리하지 않는다는장점

 

3-1.Custom reactions

Custom reactions can simply be created using the autorun, reaction or when functions to fit your specific situations.

For example the following autorun prints a log message each time the amount of unfinishedTodoCount changes:

-> 특정 상황에 맞게 쓰는 when, reaction 은 알고 있을테지만 autorun은 밑에 코드를 봐둘만한 의미가 있다.

 

1
2
3
autorun(() => {
    console.log(`Tasks left: ${todos.unfinishedTodoCount}`)
})
cs

unfinishedTodoCount의 값이 변할때마다 autorun 메서드가 로그를 찍게 된다.

What will MobX react to?

Why does a new message get printed each time the unfinishedTodoCount is changed? The answer is this rule of thumb:

->그렇다... 경험 법칙? 이라고한다.... 뭐지?

MobX reacts to any existing observable property that is read during the execution of a tracked function.

-> @observable 이 추적된다고하네요 실행되는동안. 자세한 예시는 밑에 링크 가라고 합니다. ㅎㅎ

For an in-depth explanation about how MobX determines to which observables needs to be reacted, check understanding what MobX reacts to.

 

Unlike many flux frameworks, MobX is unopinionated about how user events should be handled.

  • This can be done in a Flux like manner.
  • Or by processing events using RxJS.
  • Or by simply handling events in the most straightforward way possible, as demonstrated in the above onClick handler.

 --> Flux 가 뭔지 모르겠음... , RxJS도 뭔지 모르겠음...

현재의 나는 onClick 이벤트 처리를 이용해 mobx를 움직이고 있다.... 

***Flux 설명

 위에 링크를 통해 내용을 파악하는게 좋고 간단히말하면 

 

 이런 데이터 흐름인데 mobx와 매우 비슷하다..

***RxJS (반응형 프로그래밍 패러다임이다.) 

 RxJS는 반응형 프로그래밍으로 Observer 패턴, Iterator패턴 등 조합하여 사용하는 Observable이라는 객체로 표현한 후 비동기 이벤트 기반의 프로그램 작성을 하기도하고 이또한 Mobx와 비슷하다.

 

 

There is no technical need for firing events, calling a dispatcher, etc. A React component in the end is nothing more than a fancy representation of your state, i.e. a derivation that will be managed by MobX.

->이벤트 발생, 디스패처 호출 등의 기술적 인 필요는 없습니다. 결국 React 컴포넌트는 상태의 멋진 표현, 즉 MobX가 관리 할 파생물에 지나지 않습니다.

 

 

그리고 이제 간략한 개념설명들을 했으니 자랑질이 시작되시겠다.

MobX: Simple and scalable

MobX is a simple, very scaleable and unobtrusive state management library.

좋은 상태 라이브러리다.

부터해서 자랑질 ~~

 

MobX 4 vs MobX 5

The difference between MobX 4 and MobX 5 is that the latter uses Proxies to do property tracking. As a consequence, MobX 5 runs only on Proxy supporting browsers, in contrast to MobX 4 that runs on any ES 5 environment.

The most notable limitations of MobX 4:

  • Observable arrays are not real arrays, so they won't pass the Array.isArray() check. The practical consequence is that you often need to .slice() the array first (to get a real array shallow copy) before passing to third party libraries.
  • Adding properties to existing observable objects after creation is not automatically picked up. Instead, either use observable maps or use the the built-in utility functions to read / write / iterate objects that you want to dynamically add properties to.

For more details see the caveats page.

 

와같이 둘의 차이점을 설명으로 깃허브 README.md 파일은 마무리가 된다.

 

깃허브에는 첨부된 파일들이 있으니 실행해보고 실제 돌아가는 코드를 접할수 있으니 깃허브 Document의 장점이라 생각해.. 보통 기본 사이클 + 돌아가는 형식을 보고싶다면 (어느정도 수준이있는 프로그래머) 는 github를 보는거 같더라구 ㅎㅎㅎ

 

챕터별로 상세한 Document가 필요하다면 mobx 사이트의 document를 참조해야 할거야 ㅎㅎ

 

 

다음장에는 document말고 숙지한 내용으로 정리를할께

이만 물러갈께 ㅎ

 

 

 

 

'JS > Mobx' 카테고리의 다른 글

Mobx Start  (0) 2019.09.12