React LifeCycle

Jay·2021년 1월 4일
0

Life Cycle

: 매 중요한 순간마다, 컴포넌트는 새로 렌더링 된다.
그 중요한 순간들을 제어하기 위한 방법이다.

라이프사이클 메소드

- componentDidMount

: 화면에 등장한 후

- componentDidUpdate

: 컴포넌트가 새로운 상태를 가지고 난 후

- componentWillUnmount

: 화면에서 사라지기 전

라이프사이클 메소드 활용예제

시계 만들기
1. componentDidMount를 활용하여 1초마다 tick함수를 작동하게 하였다.
2. componentWillInmount를 활용하여 시계가 작동하지 않도록 해주었다.
function FormattedDate(props) {
  return <h2>It is {props.date.toLocaleTimeString()}.</h2>;
}

class Clock 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>
        <h1>Hello, world!</h1>
        <FormattedDate date={this.state.date} />
      </div>
    );
  }
}

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

시계 완성

profile
programming!

0개의 댓글