[React.js] 5. State and Lifecycle

2021. 7. 20. 00:32개발/React.js

반응형

예전에 React-Native앱을 만들 당시 state, lifecycle 과 씨름한 적이 있었는데, 공식문서에서 만나보니 또 새롭다.

다른 형태의 App들도 그렇듯, lifecycle은 꼭 먼저 살펴보고 지나가는 것이 좋았었다.

 

 

이전 강좌를 통해 배운 것은 setInterval을 통해 rerendering 하는 방법을 배웠었다. (아래처럼)

 

function tick() {
  const element = (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {new Date().toLocaleTimeString()}.</h2>
    </div>
  );
  ReactDOM.render(
    element,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

 

state 라는 녀석을 사용하게 되면, state가 바뀔때 자동으로 rerendering 할 수 있다.

 

그러기위해서는 먼저 함수를 클래스로 변환해야하는데, React에서는 아래와 같이 5단계로 나누어 설명하고 있다.

다섯 단계로 Clock과 같은 함수 컴포넌트를 클래스로 변환할 수 있습니다.
1. React.Component를 확장하는 동일한 이름의 ES6 class를 생성합니다.
2. render()라고 불리는 빈 메서드를 추가합니다.
3. 함수의 내용을 render() 메서드 안으로 옮깁니다.
4. render() 내용 안에 있는 props를 this.props로 변경합니다.
5. 남아있는 빈 함수 선언을 삭제합니다.

 

글자로 보면 어렵다.... 직접 코드로 옮기면 아래와 같이 구성할 수 있게 된다.

 

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

 

function -> class 로 바꾸면서 React.Component를 상속받았다. (function일때와는 달리 React.Component 의 내용을 사용할 수 있게 된것이다.)

 

 

React에서 Class component는 항상 props로 기본 constructor를 호출해야한다고 한다.

그리고 state는 key와 value 쌍으로 관리한다.

 

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

 

React 를 진짜 잘다루시는 분들은 어떻게 하는지 모르겠지만, update가 필요한 component를 생성할때는 기계처럼 아래와 같은 포맷을 만들어두고 하는것이 편하다.

 

class [CLASSNAME] extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
    
    };
  }

  render() {
    return (
      
    );
  }
}

 

여기서 조금은 어색할 수도 있지만 state값을 수정할때는 직접수정 하지 못한다.

꼭! setState를 사용해야 state 값이 변경되고, 그 값이 UI에 반영된다.

// Wrong (직접 수정은 불가하다.)
this.state.comment = 'Hello';

// Correct (setState()를 통해 state를 바꿔야한다.)
this.setState({comment: 'Hello'});

 

 

 

 

 

 

 

Life Cycle


Life Cycle 즉, 생명주기에 대해 알아보자~

React에서는 DOM에 렌더링되는 것을 Mounting이라고 불린다. 

다양한 이름의 생명주기가 존재하지만, 주로 썼었던 녀석은 아래 두가지였다.

1. componentDidMount -> Rendering 이후 호출되는 함수

2. componentWillUnmount -> unmount 이후 호출되는 함수 (더 이상 사용하지 않을때 호출)

 

공홈을 뒤적거리면, 더 자세한 내용을 배울 수 있지만 지금은 간략하게 넘어가는것이 좋을거같다.

(https://ko.reactjs.org/docs/react-component.html)

React Life Cycle

 

 

 

 

 

 

전체 연습 코드


<html>
  <head>
    <!-- Load React. -->
    <!-- Note: when deploying, replace "development.js" with "production.min.js". -->
    <script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

  </head>
  <body>
    <div id="root"></div>
    <script type="text/babel">
      class Comp extends React.Component {
        constructor(props) {
          super(props);
          this.state = {
            date: new Date()
          };
        }

        componentDidMount() {
          this.timerID = setInterval(()=>this.tick(), 1000);
        }

        componentWillUnmount() {
          clearInterval(this.timerID);
        }

        tick() {
          this.setState({
            date: new Date()
          });
        }

        render() {
          return(
            <div>
              {this.state.date.toLocaleTimeString()}
            </div>
          )
        }
      }

      const e = <Comp/>

      ReactDOM.render(e, document.getElementById('root'));
    </script>
  </body>
</html>
반응형

'개발 > React.js' 카테고리의 다른 글

[React.js] StopWatch 구현하기  (0) 2021.07.21
[React.js] 6. Event  (0) 2021.07.20
[React.js] 4. Component와 Props  (0) 2021.07.19
[React.js] 0. Self Study  (0) 2021.07.19
[React.js] 3. Element Rendering (엘리먼트 렌더링)  (0) 2021.07.19