TIL # 36 (React intro 3)

Mikyung Lee·2021년 1월 27일
0
post-thumbnail

4. React 컴포넌트의 Lifecycle

컴포넌트의 life cycle에 대해 알아보자. 컴포넌트를 만들 때 class로 생성하면 아래의 메서드를 사용할 수 있고, 컴포넌트가 lifecycle에 따라 각자의 메서드가 호출된다.

1초에 한 번 tick함수를 호출해서 현재시간을 초 단위로 업데이트 해보자.

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);

화면으로 보여줄 부분을 함수를 사용해서 컴포넌트로 만들기

function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);

매초 업데이트될 기능이 Clock 컴포넌트 내에서 이루어져야 하므로 class 컴포넌트를 만들기

class Clock extends React.Component {
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.props.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}
  • ReactDOM.render() 에서 첫 인자로 를 넘길 때, React는 Clock 컴포넌트의 constructor를 호출한다.
  • Clock에서 초기 시간이 필요하므로 this.state에 현재 시간으로 초기화했다.
  • 그리고나서 Clock 컴포넌트의 render() 메서드가 호출된다.
  • DOM에 render()의 return된 요소가 추가 되면 componentDidMount함수가 호출된다.
  • Clock 컴포넌트의 tick 메서드가 매 초 호출될 수 있도록 timer를 추가한다.
  • 매 초 브라우저가 tick 메서드를 호출하면서 this.state.date 값이 변한다.
  • state가 변경되면 원래 componentDidUpdate 함수가 호출되지만, 우리는 위에서 정의하지 않았으므로 render()가 다시 호출되면서 바뀐 부분이 변경된다.
  • DOM에서 Clock 컴포넌트가 삭제될 때, componentWillUnmount 가 호출되고 timer도 같이 멈추게 된다.
class Clock extends React.Component {

  constructor() {
    super();

    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>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);
profile
front-end developer 🌷

0개의 댓글