[React] 5. State와 LifeCycle

설정·2020년 11월 24일
0
post-thumbnail

State

  • 컴포넌트 내에서 동적으로 변동되는 데이터를 관리하며, 기본값(Default Value)이 미리 설정해야 사용할 수 있다.
  • State는 비공개이며 컴포넌트에 의해 완전히 제어된다.
  • 클래스 컴포넌트에서 사용이 가능하다. [함수형 컴포넌트는 Hooks를 사용]

클래스에 로컬 State 추가하기

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }
  render() {
    return (
      <div>
      	<h1>Hello</h1>
      	<h2>It is {this.state.date.toLocalTimeString()}</h2>
      </div>
     );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

코드해석

  1. 우선 State클래스 컴포넌트에서 사용이 가능하다.(함수형 컴포넌트는 Hooks를 사용)
  2. State를 사용하기 위해서는 초기 this.state를 지정하는 class constructor가 필요하다.
  3. ClockComponent를 상속받기 때문에 super키워드를 이용하여 부모 클래스를 상속받고, 클래스 컴포넌트는 항상 props로 기본 constructor를 호출해야 한다.

setState 사용하기

직접 State를 수정할 수 없으며, this.state 지정가능한 유일한 공간은 constructor이다.

// wrong
this.state.comment = 'Hello';

// correct
this.setState({comment: 'Hello'});

State 업데이트는 비동기적일 수도 있다.

setState() 호출은 단일 업데이트로 한꺼번에 처리가 가능하기 때문에 this.statethis.props가 비동기적으로 업데이트 될 수 있다.

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment
});

// Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.counter
}));
  • 첫 번째 인자(prevState) : 이전의 state
  • 두 번째 인자(props) : 업데이트가 적용된 시점의 props

state 업데이트는 병합된다.

setState 함수를 호출할 때 리액트는 제공한 객체를 현재 state로 병합한다.

데이터는 아래로 흐른다.

  • 컴포넌트는 자신의 state를 자식 컴포넌트에 props로 전달 할 수 있다.
  • 하향식(top-down) 또는 단방향식 데이터흐름

참고

1. class constructor

class는 객체를 생성하기 위한 템플릿이다.

- 함수 선언식과 함수 표현식

  • 함수 선언식
class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
  • 함수 표현식 : 이름을 가질 수도 있고, 갖지 않을 수도 있다.
//unNamed
let Rectangle = class {
  constructor(height, width) {
    this.height = height;
    this.width = width'
  }
}

//Named
let Rectalgle = class Rectangle2 {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

- Class body

class body는 중괄호 {}로 묶여 있는 안쪽 부분이다.

constructor(생성자)

  • constructor메서드는 class로 생성된 객체생성하고 초기화하기 위한 특수한 메서드로 클래스 안에 한 개만 존재할 수 있으며, 여러 개의 constructor 메서드가 존재할 시 SyntaxError가 발생한다.
  • constructor는 부모 클래스의 constructor를 호출하기 위해 super 키워드를 사용한다.

0개의 댓글