Mobx

송은우·2022년 2월 24일
0

observable, reaction, computed, autorun(computed로 만든 값.get())

reaction(()=>변수명=>{호출할 함수}) 

변수가 바뀌면 알아서 함수 호출을 해준다.

const 변수=computed(()=>{})
변수.observe(()=>변수명); 특정 변수 주시
변수.get(); computed내부 모든 값 알아서 참조

computed는 cashing의 느낌.

import { decorate, observable, computed, autorun } from 'mobx';

class test {
  array = [];
  
  get total() {
    console.log('calculated');
    return this.array.reduce((prev, curr) => prev + curr.val, 0);
  }

  add(name, val) {
    this.array.push({ name, val });
  }
}

decorate(test, {
  array: observable,
  total: computed,
  add:action
});

const temp = new test();
autorun(() => test.total);
temp.add('1', 800);
console.log(temp.total);
temp.add('2', 800);
console.log(temp.total);
yarn add @babel/plugin-proposal-class-properties @babel/plugin-proposal-decorators
decorator 사용

eject 후에
 "babel": {
    "presets": [
      "react-app"
    ],
    "plugins": [
        ["@babel/plugin-proposal-decorators", { "legacy": true}],
        ["@babel/plugin-proposal-class-properties", { "loose": true}]
    ]
  }

class형으로 선언되어있기에, 접근 방식이 Stord명.class할당된변수명.값 으로 접근해야함.
일반 변수는...? 어떨까?

일반 변수 할당하듯이 하면 그냥 처리 가능
이런 경우 그냥 일반 변수로 접근도 가능하게 할 수 있음'

mobx에서는 custom hooks 처리가 안됨. 그래서 observer 빼버려야됨

profile
학생의 마음가짐으로 최선을 다하자

0개의 댓글