2-3. state를 constructor에서 꺼내기

송한솔·2023년 4월 26일
0

ReactStudy

목록 보기
14/54
post-thumbnail

state를 constructor에서 꺼내기

이 코드에서 constructor와 그에 따라오는 super(props)를 지워봅니다

import React, { Component } from 'react';

class Counter extends Component {

    state = {
        number: 0,
        fixedNumber: 0
        // state를 조회할 때는 this.state로 조회합니다.
    };

    render() {
        const { number, fixedNumber } = this.state;
        return (
					...
        );
    }
}

export default Counter;

새로 고침 후 확인해보면 여전히 state가 사용이 가능한 것을 볼 수 있습니다.

이처럼 클래스 컴포넌트에서 constructor를 사용하지 않고도 state를 선언하는 것을 "클래스 필드(class fields)"라는 문법이라고 합니다.

0개의 댓글