리액트 라이프 사이클 D4

nearworld·2022년 8월 2일
0

React Lifecycle

목록 보기
4/5

render()

render() {
  return <></>
}
  1. JSX를 리턴.
  2. Virtual DOM과 Real DOM의 비교
  3. 필요한 부분만 업데이트 가능
  4. render 안에서 propsstate업데이트 시도는 하지 말아야한다. 업데이트는 렌더링 이후에 처리되도록 라이프사이클이 설계되어 있기 때문.

componentDidMount()

componentDidMount() {
  // codes..
}

render() 메서드가 실행된 이후 실행되는 메서드.
오직, Mounting 단계에서만 실행되며 Updating 단계에서는 실행되지 않는다.
state 업데이트 코드는 componentDidMount() 에 등록한다.

예시 코드

componentDidMount() {
  setTimeOut(() => {
    this.setState({ color: 'red' })
  }, 2000)
}

render() {
  return <h1 style={{color: this.state.color}}>hello world</h1>
}

setTimeOut 함수가 2초 후에 1번째 인자인 콜백 함수르를 실행하도록 했다.
componentDidMount()render 처리 후에 실행되므로 화면에 hello world 텍스트가 나온 후 2초 정도 뒤에 this.setState({ color: 'red' })가 실행된다.

profile
깃허브: https://github.com/nearworld

0개의 댓글