[React] super(props)

nothing-99·2022년 9월 7일
0

react

목록 보기
2/4
post-thumbnail

super(props)?

클래스 컴포넌트를 작성할 때 형식적으로 작성한 형태가 존재한다.

  • constructor(props)
  • super(props)
class Button extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ••• };
  }
}

[Note]

::super::

  • 부모 클래스의 constructor을 호출(참조)한다
  • this를 사용 가능하도록 한다 (즉, super()를 호출하지 않는다면 해당 클래스에서 this.~를 사용할 수 없음 -> 경고 발생!)
/*  WARNING
 *  - 'this' is not allowed before 'super()'
 */
class Counter extends React.Component {
  constructor(props) {
    this.state = { count: 0 };
  }
}

왜.. super()를 constructor 상단에 위치시킬까?
클래스에서 생성자를 실행할 때, 생성자 안에 부모 클래스의 필드(변수)를 사용하는 메서드를 실행시킨다고 생각해보자. super()는 부모 클래스의 생성자를 실행하고 부모 클래스에서 가져온 필드의 값을 초기화시킨다. 하지만 초기화되지 않은 필드를 사용하기 때문에 원하지 않은 결과를 얻을 것이다. 이것을 방지하기 위해서 자바스크립트는 상속받는 클래스의 생성자를 실행할 때 super()를 사용하도록 한다.

super()를 호출할 때 argument로 주지 않는다면?
React는 신기하게도 constructor(props)를 실행한 후에 this.props에 argument로 받은 props를 할당해준다. 하지만 허점은 존재한다. super() 와 constructor(props) 종료 사이의 틈에서 this.props를 만약에 참조한다면 undeinfed가 나온다. 그렇기 때문에 super(props)로 작성하자.

/**
 * [react/ReactBaseClasses.js at 1d25aa5787d4e19704c049c3cfa985d3b5190e0d · facebook/react · GitHub](https://github.com/facebook/react/blob/1d25aa5787d4e19704c049c3cfa985d3b5190e0d/packages/react/src/ReactBaseClasses.js#L22)
 * Base class helpers for the updating state of a component.
 */
function Component(props, context, updater) {
  this.props = props;
  this.context = context;
  // If a component has string refs, we will assign a different object later.
  this.refs = emptyObject;
  // We initialize the default updater but the real one gets injected by the
  // renderer.
  this.updater = updater || ReactNoopUpdateQueue;
}

하지만 새로운 class field를 이용한다면!! constructor, super, this 모두 신경쓰지 않아도 된다.

class Counter extends React.Component {
  state = 0;
}

참조

profile
- RAYC, Vaping Ape, Bitcoin Monkeys holder

0개의 댓글