bluelion2 / Project-issue-repo

프로젝트를 진행하면서 있던 오류와 해결을 기록하는 repo
1 stars 0 forks source link

[Mobx] mobx observable이 동작하는 원리 #31

Closed bluelion2 closed 3 years ago

bluelion2 commented 3 years ago

✨ What? 발견된 이슈 간단히 정리하기

어떻게 Mobx에서 Observable한 값을 관리를 할까?

📚 캡쳐한 사진들

bluelion2 commented 3 years ago

Mobx 5 버전 이상부터는 Es6의 Proxy 객체를 통해 상태를 관리한다. Proxy는 IE에서 지원하지 않기때문에, Mobx5버전이상부터는 IE를 지원할 수 없다 (단, 6에서는 옵션을 추가해서 객체로 관리하는 방법이 존재함)

bluelion2 commented 3 years ago

function App() {
  const [store, ] = useState(new Store())

  console.log('store', store)
  return (
    <div className="App">
      {store.value}
      <button onClick={store.increase}>+</button>
    </div>
  );
}

export default observer(App);

class Store {
  value = 10
  constructor() {
    makeAutoObservable(this)
  }

  increase = () => {
    this.value++
  }
}
bluelion2 commented 3 years ago

code mobx 공식 문서에서는 , makeObservable 또는 makeAutoObservable을 통해 해당 class를 생성할때 constructor에서 메서드들을 관찰하도록 등록을 해 둔다. (makeObservable의 경우 각각 등록해야하지만, makeAutoObservable은 따로 프로퍼티나 메스드를 전부 관찰한다.)

code

code

makeObservable은 첫번째 인자로 this를 받으며(class 자신) 두번째 인자로 객체를 받는데, 관찰할 대상의 프로퍼티, 메서드를 키로 가지면서 값으로는 mobx 내장 함수를 받는다. (관찰할 값은 observable, 메서드는 action 등)

code

var keys = ownKeys({ a: 10, b: false })
console.log('keys', keys) // ['a', 'b']

makeObservable() 함수를 통해서 받은 값을 관찰 할수 있는 option들이 달린ObservableObjectAdministration symbol로 만들어서 해당 값들을 관리한다.

스크린샷 2021-06-24 오후 11 58 17

스크린샷 2021-07-03 오후 6 08 13
bluelion2 commented 3 years ago

Mobx observable - 내부구조 코드와 observable.prototype

observable객체 안에서, createObservable()과 프로퍼티의 메서드를 정의

c

code

bluelion2 commented 3 years ago

자바스크립트의 함수는 객체이다. 따라서 해당 코드처럼도 가능함. code

bluelion2 commented 3 years ago

값을 set 할떄 작동하는 함수

code

bluelion2 commented 3 years ago

Spy() 를 통해 해당 값이 관찰 되게 한다.

spy

spyReport()가 관찰할 대상을 globalState에 담아서 관리하기 시작

code

bluelion2 commented 3 years ago

observableValue의 값을 get 할 때에도, 관찰 된 것인지 확인한후 리턴함. code

bluelion2 commented 3 years ago

객체 형태는 기본적으로 Proxy로 바꾸어서 사용함.

code1 code

bluelion2 commented 3 years ago

mobx-react 는 내부적으로 mobx-react-lite를 가져다 쓰고 있다. observer로 래핑한 컴포넌트에서, 관찰하는 값이 바뀌면 리렌더를 시작한다. code1

observer(component) 내부에서는 또 useObserver를 쓰는데, 여기가 핵심 로직 code12

bluelion2 commented 3 years ago

code

bluelion2 commented 3 years ago

observer의 역할

ezgif com-video-to-gif

observer

bluelion2 commented 3 years ago

스크린샷 2021-07-03 오후 8 06 11