재우니의 블로그

 

https://reactant.js.org/docs/state-action

 

Reactant · A framework for building React applications

A framework for building React applications

reactant.js.org

 

@state 및 @action

Reactant는 React의 불변의 공유 state 를 장식(decorating)하는 @state 를 제공하며, state 변경 업데이트를 장식(decorating)하는 @action 도 제공합니다. 이것은 Redux 와 Immer 을 기반으로 되어 있습니다.

@state

다음 예제 list 에서 Foo 모듈은 React의 공유 state 가 아니며, 변경된 위치에서 React 컴포넌트로 자동 업데이트 될 수 없지만, @state 에 의해 데코레이션 된 속성 즉, count 는 어디서든 React 의 state 를 공유됩니다.

@injectable()
class Foo {
  list = [];

  @state
  count: number = 0;
}

 

@action

@action은 현재 모듈의 상태를 업데이트하는 방법을 decorate 합니다. 다음 예제의 증가는 현재 모듈의 state 를 업데이트하는 데 사용할 수 있는 방법입니다.

Reactant 모듈 상태 관리는 Redux 기반입니다. 이것은  Immer 을 사용하기 위해, 일반적으로 사용하는 mutation 업데이트 작업과 동일합니다.

@injectable()
class Foo {
  list = [];

  @state
  count: number = 0;

  @action
  increase() {
    this.count += 1;
  }
}

 

메소드가 @action로 장식되어 있지만 상태 값을 변경하려고하면 기본적으로 UI에 자동으로 업데이트되지 않지만 createApp 인터페이스 devOptions가 {autoFreeze : true}로 설정되어있는 경우, 상태 업데이트하려는 @action로 장식되어(decorated) 있지 않으면 오류가 발생합니다.

 

따라서 개발 모드에서는 autoFreeze을 활성화하고 실전 모드에서는 autoFreeze을 해제 할 것을 권장합니다 (해제하지 않으면 성능이 저하 될 수 있습니다).

 

Tips

  • @state 와 @action 둘다 상속 지원이 됩니다.

@injectable()
class Foo {
  @state
  count: number = 0;

  @action
  increase() {
    this.count += 1;
  }
}

@injectable()
class Foo1 extends Foo {
  @state
  count: number = 0;

  @action
  increase() {
    super.increase();
    this.count += 1;
  }
}

 

@action는 다른 업데이트 상태를 실행하여, 업데이트를 UI에 병합하는 다른 액션의 호출을 지원합니다 (현재 모듈 상태이어야하지만, 모듈 간의 상태는 1 개씩 업데이트됩니다 ).

@injectable()
class Foo {
  @state
  list: number[] = [];

  @state
  count: number = 0;

  test: string = 'test';

  // `increase()` will combine update `list` and `count` state.
  @action
  increase() {
    this.count += 1;
    this.list(this.count);
  }

  @action
  add(text: number) {
    this.list.push(text);
  }
}