본문 바로가기

Front/React

React - 데이터의 변화 (props, state)

props

 

부모가 자식한테 전달해주는 데이터 (읽기전용)


state

import React, { Component } from 'react';

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

  // 화살표 함수가 아닌 일반 함수로 정의할 경우 this가 뭔지 인식하지 못함.
  handleIncrease = () => {
    // this.state.number = this.state.number + 1;
    // 이렇게 하면 state값이 업데이트 됐는지를 Component 자신이 모른다.
    this.setState({
      number: this.state.number + 1
    });
  };

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

  render() {
    return (
      <div>
        <h1>카운터</h1>
        <div>값: {this.state.number} </div>
        <button onClick={this.handleIncrease}>+</button>
        <button onClick={this.handleDecrease}>-</button>
      </div>
    );
  }
}

export default Counter;
class Counter extends Component {
  state = {
    number: 0
  };

//this를 인식할 수 있게 bind 해줌.
  constructor(props) {
    super(props);
    this.handleIncrease = this.handleIncrease.bind(this);
    this.handleDecrease = this.handleDecrease.bind(this);
  }

  handleIncrease() {
    this.setState({
      number: this.state.number + 1
    });
  };

  render() {
    return (
    );
  }
}

 

 

정리.

state는 컴포넌트 안에 있으며, 값을 변경할때는 항상 setState() 함수를 사용해야한다.

setState()를 사용해서 값이 바뀌게 되면 자동으로 rerendering을 해서 화면에 반영한다.

 

 


 

setState 함수의 종류

 

1. setState(newState)

새로운 state오브젝트를 인자로 바로 받는 함수

 

2. setState(prevState => { return newState; })

이전 state를 받아서 그걸로 계산해서 새로운 state를 리턴하는 함수를 인자로 받는 함수

 

(예)

<button

onClick = { () => {

                 this.setState( state => ({ count : state.count+1 }) );

                }}

>

click

</button>