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

this.Setstate() 사용

this.Setstate()는 render() 함수 내에서 호출 할 수 없다!

이를 사용하기 위해서 새로운 함수를 정의하고 사용법을 알아보자.

이전 포스트에서 언급했다시피, state를 사용하려면 constructor 매서드와 그 내부에 state property를 선언해야 한다.

또한 React에서 this keyword를 이용한 이벤트 핸들러를 선언하기 위해선 bind 작업 this.methodName = this.methodName.bind(this)

constructor 내부에 해주어야 한다.

이와 관련하여 자세히 알아보려면 https://reactjs.org/docs/handling-events.html < 여기 참조하시고

일단은 아래 예제 코드를 통해 setState() 의 사용을 살펴보자

예) 클릭 이벤트로 상태 변경하기 (background color 변경)

    import React from 'react';
    import ReactDOM from 'react-dom';
    
    const green = '#39D1B4';
    const yellow = '#FFD712';
    
    class Toggle extends React.Component {
      constructor(props){    // state 사용을 위해 constructor와 state 선언 
        super(props);
        this.state = { color : green }
        this.changeColor = this.changeColor.bind(this);  //onClick 이벤트 핸들러 사용을 위한 bind 
      }
      
      changeColor() {
        const newColor = this.state.color == green ? yellow : green ;  // green이면 yellow 반환, yellow이면 green 반환
        this.setState({ color: newColor });
      }
      
      render() {
        return (
          <div style=>  //화면의 background color 변환을 위해 사용할 attribute 할당 
            <h1>
              Change my color
            </h1>
            <button onClick={this.changeColor}>        // onClick 이벤트 핸들러 사용 
              Change color
            </button>
          </div>
        );
      }
    }
    
    ReactDOM.render(<Toggle />, document.getElementById('app'))

실행결과

여기서 한가지 흥미로운 사실!

changeColor 함수는 사실 this.setState() 만을 실행시켜서 this.state.color 값만 변경할 뿐인데

화면의 backgound color가 변경되는 것을 확인 할 수 있다.

사실 화면을 변경하려면 <Toggle />이 랜더링 되어야 하는데 말이다!

즉, this.setState()가 실행될 때 자동적으로 render()를 실행된다는 뜻이다.

그렇기 때문에 앞서 언급했듯이 render() 내부에서는 setState()를 호출할 수 없는 것이다!