Closed bluelion2 closed 3 years ago
Mobx 5 버전 이상부터는 Es6의 Proxy 객체를 통해 상태를 관리한다. Proxy는 IE에서 지원하지 않기때문에, Mobx5버전이상부터는 IE를 지원할 수 없다 (단, 6에서는 옵션을 추가해서 객체로 관리하는 방법이 존재함)
var obj = {}
var newObj = {
get: function (obj, name) {
return name in obj ? obj[name] : undefined
},
set: function(obj, property, value) {
obj[property] = value
}
}
var proxy = new Proxy(obj, newObj)
proxy.a = 10
proxy.b = 11
console.log(proxy.a) // 10
console.log(proxy.dd) // undefined
console.log(obj.a) // 10
console.log(obj == proxy) // false
console.log(typeof proxy) // object
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++
}
}
mobx 공식 문서에서는 , makeObservable
또는 makeAutoObservable
을 통해 해당 class를 생성할때 constructor에서 메서드들을 관찰하도록 등록을 해 둔다. (makeObservable의 경우 각각 등록해야하지만, makeAutoObservable은 따로 프로퍼티나 메스드를 전부 관찰한다.)
makeObservable은 첫번째 인자로 this를 받으며(class 자신) 두번째 인자로 객체를 받는데, 관찰할 대상의 프로퍼티, 메서드를 키로 가지면서 값으로는 mobx 내장 함수를 받는다. (관찰할 값은 observable
, 메서드는 action
등)
var keys = ownKeys({ a: 10, b: false })
console.log('keys', keys) // ['a', 'b']
makeObservable()
함수를 통해서 받은 값을 관찰 할수 있는 option들이 달린ObservableObjectAdministration
symbol로 만들어서 해당 값들을 관리한다.
observable객체 안에서, createObservable()과 프로퍼티의 메서드를 정의
자바스크립트의 함수는 객체이다. 따라서 해당 코드처럼도 가능함.
값을 set 할떄 작동하는 함수
spyReportStart()
실행값이 바뀌었는지 확인하고, globalState에 바뀐 것을 등록함.
새롭게 변경된 값을 전파
전파를 받으면 사용되는 곳을 조회하기 시작함.
Spy()
를 통해 해당 값이 관찰 되게 한다.
spyReport()
가 관찰할 대상을 globalState
에 담아서 관리하기 시작
observableValue의 값을 get
할 때에도, 관찰 된 것인지 확인한후 리턴함.
객체 형태는 기본적으로 Proxy로 바꾸어서 사용함.
mobx-react 는 내부적으로 mobx-react-lite를 가져다 쓰고 있다. observer로 래핑한 컴포넌트에서, 관찰하는 값이 바뀌면 리렌더를 시작한다.
observer(component)
내부에서는 또 useObserver를 쓰는데, 여기가 핵심 로직
observer의 역할
observer()로 래핑함으로써 컴포넌트가 리렌더링 되게 한다.
(내부적으로 쓰고 있기 때문에), 공식문서에서도 memo를 쓸 필요가 없다고 한다.
✨ What? 발견된 이슈 간단히 정리하기
어떻게 Mobx에서 Observable한 값을 관리를 할까?
📚 캡쳐한 사진들