ABOUT ME

-

Today
-
Total
-
  • React state 동적인 상태값
    Study/React 2020. 1. 14. 11:52
    반응형

     

    state

    동적으로 바뀌는 값을 관리할 때 state 라는 것을 사용한다.

    props와 달리 state는 읽기 뿐만 아니라 값을 바꾸며 업데이트할 수 있다.

    state가 업데이트 될 때 마다 리렌더링된다.

    참고로 렌더링해서 return 하는 코드에는 최대한 함수 로직을 넣지 않는다.

    리렌더링 될 때 마다 함수를 새로 만드는 것은 낭비이기 때문이다.

     

    클래스형 컴포넌트의 state

     

    - constructor 내부에서 this.state로 초기값을 설정해준다.

    - state는 반드시 객체 형태이어야 한다.

    - render 메서드에서 state를 조회하려면 this.state를 조회하면 된다.

    - this.setState 함수로 state 를 업데이트 할 수 있다.

    - state내부에 또 다른 객체 값이 있다면, 불변성 유지를 위해 spread 함수를 사용해야한다.

     

    import React, { Component } from 'react';
    
    class Counter extends Component {
      constructor(props) {
        super(props);
        this.state = {
          counter: 0,
          toggle: {
            dontChange: 1,
            change: true
          }
        };
      };
      
      handleIncrease = () => {
        this.setState({
          counter: this.state.counter + 1
        });
      };
    
      handleDecrease = () => {
        this.setState({
          counter: this.state.counter - 1
        });
      };
      
      handleToggle = () => {
        this.setState({
          toggle: {
            ...this.state.toggle,
            change: !this.state.toggle.change
          }
        });
      }
      
      render() {
        return (
          <div>
            <h1>{this.state.counter}</h1>
            <button onClick={this.handleIncrease}>+1</button>
            <button onClick={this.handleDecrease}>-1</button>
            <p>고정된 값: {this.state.toggle.dontChange}</p>
            
            <button onClick={this.handleToggle}>toggle</button>
            {{this.state.toggle.change} ? <p>HELLO</p> : <p>BYE</p>}
          </div>
        );
      }
    }
    
    export default Counter;

     

     

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

     

    : state 초기값 설정

     

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

     

    : state 업데이트할 때는 this.setState() 함수에 객체를 넣고 객체 안에 업데이트하고자 하는 값을 넣어서 호출하면 된다.

      사용할 함수는 return 이전에 작성해준다.

     

     

      handleToggle = () => {
        this.setState({
          toggle: {
            ...this.state.toggle,
            change: !this.state.toggle.change
          }
        });
      }

     

    : state 안에 객체 형태의 상태가 있다면 불변성 유지를 위해 spread 함수를 사용해 복사한 후 업데이트 작업을 해야한다.

     

     

    ** state 설정

     

    실무에서는 constructor, super 등을 사용하지 않고

    state = { 
          counter: 0
        }; 
      }

     

    이렇게 작성하는 경우도 많다고 한다.

     

    함수형 업데이트

     

    setState도 함수형 업데이트를 할 수 있는데, 보통 한 이벤트 함수 내에서

    setState를 여러번 연속으로 진행해야하는 경우에 주로 사용한다.

     

      handleIncrease = () => { 
        this.setState((state) =>

       return
          counter: state.counter + 1 
        }); 
      };

     

    이런 식으로 state를 인자로 가져와서 함수형으로 업데이트 해준다.

     

     

    setState는 단순히 상태를 바꾸는 함수가 아니라, 바꿔달라고 요청해주는 함수이다.

    따라서 리액트에서는 상태가 바로 업데이트 되는 것이 아니라 비동기적으로 업데이트가 된다.

    상태가 업데이트 되고난 후에 어떠한 작업을 하고 싶다면 setState 함수의 두 번째 파라미터에 콜백함수를 넣어준다.

     

      handleIncrease = () => { 
        this.setState((state) =>

       return 
          counter: state.counter + 1 
        },

        () => {console.log('increase')}

        ); 
      };

     

     

    함수형 컴포넌트의 state

     

    https://xiubindev.tistory.com/97

    반응형

    댓글