React

[React] state

썽연 2021. 10. 8. 00:28
728x90

state는 컴포넌트 내부에서 바뀔 수 있는 값을 의미한다.

props는 컴포넌트가 사용되는 과정에서 부모 컴포넌트가 설정하는 값이며,

컴포넌트 자신은 해당 props를 읽기 전용으로만 사용할 수 있다.

 

컴포넌트에 state값을 설정할때는 constructor 메서드를 작성하여 설정한다.

constructor(props) {
    super(props);
    this.state = {
      number: 0,
    };
  }

컴포넌트의 생성자 메서드로, 

클래스형 컴포넌트에서 constructor를 작성할 때는 반드시 super(props)를 호출해주어야함.

함수가 호출 시, 클래스형 컴포넌트가 상속받고 있는 리액트의 컴포넌트 클래스가 지닌 생성자 함수 호출..

 

this.state에 초기값 설정. 컴포넌트 state는 객체형식

 

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

 

setState함수는 state값을 바꿀 수 있게 해주는 함수!!

 

 

state의 초기값을 지정하기 위해 constructor 메서드를 선언해주었지만,

다른 방식으로 state의 초깃값 지정 가능.

 

class Counter extends Component {
  state = {
      number: 0,
      fixednumber: 0,
    };

constructor인 생성자 메서드와

super이 빠짐!

 

728x90