클래스 컴포넌트에서 상태구현

최 재성·2023년 5월 30일

React

목록 보기
3/15

클래스 컴포넌트에서 상태는 항상 state 라는 이름의 멤버 속성으로 구현해야 한다는 제약 조건이 있음.

state 속성에 멤버 속성을 만들고 초깃값을 설정해 제약 조건을 만족.
render() 메서트에서 this.state. 형태로 멤버 속성값 얻을 수 있음.

import { Component } from 'react'
import { Title } from '../components'

export default class ClassLifecycle extends Component {
  state = {
    today : new Date
  }
  render() {
    //비구조 할당 구문
    const {today} = this.state
    
    return (
      <section className="mt-4">
        <Title>ClassLifecycle</Title>
        <div className="flex flex-col items-center mt-4">
          <p>{today.toLocaleDateString()}</p>
          <p>{today.toLocaleTimeString()}</p>
        </div>
      </section>
    )
  }
}

모든 클래스 컴포넌트의 부모 클래스인 Component클래스가 제공하는 setState()는 state 라는 이름의 멤버 속성을 가지고 있다는 가정으로 설계된 메서드, 클래스 컴포넌트가 상태를 가지려면 반드시 state라는 멤버 속성이 있어야함.

 state = {
    today: new Date(),
    interverId: null as unknown as NodeJS.Timer
    //Type Assertion(타입단언),
    //타이머 함수 사용시 숫자가 아닌 NodeJs.Timer,Timeout 반환
  }
//컴포넌트 생성 직전 호출
  componentDidMount() {
    const duration = 1000
    const interverId = setInterval(() => this.setState({ today: new Date() }), duration)
    this.setState({ interverId })
  }
//컴포넌트 소멸 직전 호출, clearInterval 메모리 누수 방지.
  componentWillUnmount() {
    clearInterval(this.state.interverId)
  }

0개의 댓글