[TIL] 0522

yoon Y·2022년 5월 23일
0

Vanilla TS 프로젝트

생성될 때 모든 초기 상태를 받아서 컴포넌트 내부의 this.state에 자동으로 할당할 지, props을 따로 받고 필요한 것만 상태에 수동으로 할지 고민..
컴포넌트 내부에서 state를 지정하게되면 사용할 때마다 undefined제외 로직을 작성해주어야하기 때문.

 state: StateType | undefined;
// this.state는 생성자 함수에서 만들어지지 않기 때문에 이런 타입이 된다..

connectChild() {
    if (!this.state) return; 
    const { contentListData } = this.state;
    ...
  }

기존 방법인 props를 받아서 컴포넌트 내부에서 state를 설정하는 로직이 불필요하다고 판단해 삭제하고 컴포넌트 생성 시 initialState를 받아서 자동으로 state가 세팅되도록 변경.


// 베이스 컴포넌트 - 기존
export default class Component<PropsType, StateType> {
  $node: Element;
  props: PropsType;
  state: StateType | undefined;
  constructor($node: Element; props: PropsType) {
    this.$node = $node;
    this.props = props;
    this.setup();
    this.fetch();
    this.render();
    this.setEvent();
  }

// 베이스 컴포넌트 - 변경
export default class Component<StateType> {
  $node: Element;
  state: StateType;
  constructor($node: Element, initialState: StateType) {
    this.$node = $node;
    this.state = initialState;
    this.setup();
    this.fetch();
    this.render();
    this.setEvent();
  }
profile
#프론트엔드

0개의 댓글