[React] Component (클래스형)

ksj0314·2024년 1월 26일
0

React

목록 보기
3/27

State

1) state의 선언

this.state = { 변수명: 초기값, ... };

// JSX
class Counter extends React.Component{
	constructor(props){
        super(props);

        this.state = {
            count: 0,
  			countable: true,
        };
    }
~~~
  • 클래스형 Component의 경우 state를 생성자에서 정의합니다.
  • 여러 값의 저장이 가능합니다.

2) state의 값 변경

this.setState({ 변수명: 바꿀값 });

// JSX
~~~
    this.setState({
        count: this.state.count+1
    });
~~~

or

// JSX
~~~
    const { count } = this.state;
    this.setState({
        count: count+1
    });
~~~
  • setState를 이용하여 수정해야합니다. (setState로 수정될 때 리렌더링 됩니다.)

3) 예시

버튼을 눌러 1씩 증가시키는 component

// JSX
import React from "react";

class Counter extends React.Component{
    constructor(props){
        super(props);

        this.state = {
            count: 0,
  			countable: true,
        };
    }

  	render() {
  		const { count } = this.state;
        return(
            <div>
                <p>{count}</p>
                <button onClick={() => {
                    this.setState({
                        count: count+1
                    });
            	}}>
            	+</button>
            </div>
		);
	}
}

export default Counter;

Lifecycle

클래스형 component에서 lifecycle은 크게 세가지로 관리됩니다.

1) componentDidMount()

  • component가 마운트된 직후 호출
  • 초기화작업, 데이터의 구독, 네트워크 요청등의 작업에 적절합니다.
  • setState()를 호출할 시 주의합니다.

2) componentDidUpdate()

  • component가 업데이트 될 때 호출
  • 적절한 조건문을 사용하여 사용합니다.

3) componentWillUnmount()

  • component가 제거되기 직전 호출
  • 타이머제거, 네트워크 요청 취소, 구독해제등의 작업에 적절합니다.
  • setState()호출시 에러가 발생합니다.

0개의 댓글