[React] Class Component

2023. 10. 2. 16:52React

728x90
반응형

1. 기본 형태

클래스 컴포넌트의 기본 형태를 먼저 보자!
ES7 React/Redux/React-Native/JS snippets Extension을 사용하고 있다면 rcc를 입력하면 기본 형태를 자동으로 입력할 수 있다.

import React, { Component } from 'react'

export default class AppClass extends Component {
  render() {
    return (
      <div>

      </div>
    )
  }
}

2. State

1) state 만들기

클래스 컴포넌트는 hook이 없다!
따라서 function 컴포넌트처럼 useState를 사용할 수 없다.

constructor 메서드 안에서 state 객체를 만들어주고 안에 필요한 state들을 요소로 넣어준다.
(이 constructor는 클래스의 객체가 생성될 때 자동으로 호출되는 생성자다.)

export default class AppClass extends Component {
  constructor(props) {
    super(props);
    this.state = {
      // 필요한 state들 작성
      counter: 0,
      value: 0,
    };
  }

  ~~~ 생략 ~~~

}

2) state 사용하기

만들어 둔 state를 사용할 때는 state 이름 앞에 this.state.을 붙여준다.

{/* state 사용하기 */}
<div>state:{this.state.counter}</div>

3) setState : state 변경하기

state의 값을 변경할 때는 this.setState() 안에 변경할 값을 다시 키: 값 형태로 넣어주면 된다.

// state 값 변경하기
this.setState({
  counter: this.state.counter + 1,
  value: this.state.value + 1,
});

3. 함수

클래스 내부의 함수는 메소드가 되기 때문에 함수 앞에 const 키워드를 붙이지 않고 바로 함수 이름(메소드 이름)으로 만들어준다.

사용할 때는 state를 사용하는 것과 마찬가지로 this.메서드명

export default class AppClass extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0,
      value: 0,
    };
  }

  // 함수 만들기
  increase = () => {
    this.setState({
      counter: this.state.counter + 1,
      value: this.state.value + 1,
    });
  };

  render() {
    return (
      <div>
        <div>state:{this.state.counter}</div>
        <button onClick={this.increase}>클릭</button>
      </div>
    );
  }
}

4. LifeCycle

1) Mounting

컴포넌트가 생성될 때 실행되는 것들

constructor()

  • state를 생성한다.

render()

  • UI를 그리는 작업을 담당한다.

componentDidMount()

  • 주로 API 호출을 많이 한다.
  componentDidMount() {
    console.log("componentDidMount");
  }

2) Updating

  • state가 업데이트 되거나
  • 새로운 props가 전달되거나
  • 강제 업데이트 forceUpdate()가 일어날 경우

componentDidUpdate()

  • state가 업데이트된 이후에 실행할 로직을 작성한다.
  componentDidUpdate() {
    console.log("componentDidUpdate", this.state);
  }

3) Unmounting

componentWillUnmount()

  • 컴포넌트가 종료될 때 실행할 로직을 작성한다.
  componentWillUnmount() {
    console.log("componentWillUnmount");
  }
728x90
반응형

'React' 카테고리의 다른 글

[React] Router (version 6)  (0) 2023.10.02
[React] Describing the UI  (2) 2023.09.27
[React] Quick Start :: 80% of React concepts  (0) 2023.09.12