출처: https://www.codecademy.com

state 초기값 설정

React component는 propsstate를 통해 동적으로 접근할 수 있다.

하지만 stateprops와 다르게 외부에서 선언된 값이 넘어오는 것이 아니라 컴포넌트 내부에 자체 state를 사용한다.

컴포넌트에 state를 설정하려면 constructor 매서드 내부에 state property를 선언해야 한다.

아래 예제를 살펴보자

    class Example extends React.Component {
      constructor(props) {
        super(props);    //React 컴포넌트에서 constructor를 사용할 때 super()가 꼭 호출되어야 한다.
        this.state = { mood: 'decent' };
      }
    
      render() {
        return <div></div>;
      }
    }
    
    <Example />

Access a Component’s state

컴포넌트의 state를 읽어오려면, this.state.name-of-property

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    class App extends React.Component {
    	// constructor method begins here:
      constructor(props){
        super(props);
        this.state = {title: 'Best App'};
      }
    
      render() {
        return (
          <h1>
            {this.state.title}
          </h1>
        );
      }
    }
    
    ReactDOM.render(<App />, document.getElementById('app'))

실행결과

state update

setState() 을 사용하여 값을 update 할 수 있다.

    import React from 'react';
    
    class Example extends React.Component {
      constructor(props) {
      	super(props);
        this.state = {
          mood:   'great',
          hungry: false
        };
      }
      
      changeMood() {
          this.setState({ mood: 'bad' });
      }
    
      render() {
        return <div></div>;
      }
    }
    
    <Example />
    

changeMood() 함수를 실행시키면 hungry값은 false로 유지한 채 mood값을 ‘bad’로 update할 수 있게된다.