본문 바로가기
카테고리 없음

[2] Props, State

by mingule 2020. 7. 8.

 State 란? 

앞에서 Props를 배웠다. Props는 자식 입장에서 읽기 전용이라고 했당.

State는 그것보다 자기주도적이당.

Props에서는 부모가 자식한테 너의 name은 이거야! 라고 전해줬다면

State는 자식 컴포넌트가 자체적으로 처음부터 name을 가지고 있는다.

그리고 값을 변경하고 싶을 때에는 컴포넌트의 내장함수인 setState를 사용해 변경해준다.

값이 바뀔 때는 다시 렌더링됨!


 실습해 볼까yo - Counter 만들기 

import React, { Component } from 'react';

class Counter extends Component {
  state = {
    number: 0
  }; // state는 객체{}여야 합니다! 문자열이나 숫자면 안돼용

  handleIncrease = () => {
    // this.state.number = this.state.number + 1
    // 이렇게 하면 절대로 안돼용. 그러면 컴포넌트에서 State 값이 업데이트 됐는지 안됐는지 모릅니당.
    // 아래와 같이 만들어 주셔야 합니다.
    this.setState({
      number: this.state.number + 1
    });
  };

  handleDecrease = () => {
    this.setState({
      number: this.state.number - 1
    });
  };

// [1] 먼저 버튼을 눌러 값을 업데이트 해 줄 JSX를 만듭니다.
  render() {
    return (
      <div>
        <h1>카운터 입니당</h1>
        <div>값 : {this.state.number} </div>
        // onClick 이벤트를 주어 increase, decrease가 될 수 있게 만들어 줍니다.
        <button onClick={this.handleIncrease}>+</button>
        <button onClick={this.handleDecrease}>-</button>
      </div>
    );
  }
}

export default Counter;

그러면 왜 화살표 함수를 써야 할까요?

우리가 위의 코드의 render()에 썼던 것처럼 handleIncrease = () => 함수도 일반 함수처럼 만들게 되면, 함수 내부에서 "this"가 뭔지 알 수 없게 됩니당. (콘솔 찍어보면 에러가 나옴)

그래서 만약 화살표 함수를 쓰지 않고, 일반 함수를 쓰고싶으면, 아래처럼 하시면 됨니다요.

constructor(props) {
    // constructor는 component가 만들어질 때마다 호출되는 함수에용.
    // 그리고 여기에서 처음에 class 어쩌구 extends component 했기 때문에 컴포넌트가 가진 생성 함수를 먼저 호출해야 함니당.
    // 그래서 아래 super(props)를 통해 호출해주면 됨
	super(props);
    
    // 그리고 아래 handleIncrease, handleDecrease에서 사용되는 this가 이 constructor에서 사용하는 this다
    // 라고 알려주기 위해
    this.handleIncrease = this.handleIncrease.bind(this);
    this.handleDecrease = this.handleDecrease.bind(this);
    // 이렇게 명시해주면 됩니당. => 그럼 handleIncrease() 라고 써도 되는거에용.
    // 근데 굳이 이렇게 만들지 않고 첨부터 화살표 함수를 쓰는게 낫대용
}

조금 더 공부해 보면서 어떤 상황에서 이런 함수들을 써야 하는지 알아보는 게 좋을 것 같당.

댓글