라이프 사이클
vue도 그렇고 react도 라이프 사이클이 존재한다.
우선 라이프 사이클은 크게 세가지로 존재함
마운트, 업데이트, 언마운트
- 마운트란? DOM이 생성되고 웹 브라우저상에 나타나는 것.
이때 호출하는 메서드는 constructor, getDerivedStateFromProps,
render, componentDidMount
- 업데이트란 언제됨?
props가 바뀔 때 state가 바뀔 때, 부모 컴포넌트가 리렌더링 될 때
this.forceUpdate로 강제로 렌더링 트리거할 때
호출되는 메서드는 gerDervideStateFromProps, shouldComponentUpdate, render, getSnapshotBeforeUpdate, componentDidUpdate
- 언마운트는 언제됨? DOM에서 제거할 때
호출되는 메서드? componentWillUnmount 함수별 주의해야할 사항 & 중요사항
render() <= 이 메서드 안에서는 이벤트 설정이 아닌 곳에서 setState를 사용하면 안되고, 브라우저의 DOM에 접근하면 안됨 그렇다면 DOM정보를 가져오거나 state에 변화를 줄 때는 componentDidMount에서 처리하면 됨
componentDidMount() <= 첫 렌더링을 다 마친 후 실행함 이 안에서 다른 js라이브러리, 프레임워크의 함수 호출, 이벤트 등록, setTimeOut, setInterval, 네트워크 요청과 같은 비동기 작업을 처리하면 됨
shouldComponentUpdate(nextProps, nextState)
리렌더링을 시작할지 여부를 지정하는 메서드임 반환값을 true, false임
기본값은 true이고, false를 반환하면 업데이트가 중지됨 컴포넌트 최적화 할 때 주로 사용
getSanpshotBeforUpdate
reder에서 만들어진 결과물이 브라우저에 실제로 반영되기 직전에 호출됨 반환갑은 componentdDidupdate에서 세번째 파라미터인 snapshot 으로 받을 수 있음. 업데이트하기 직전의 값을 참고할 일이 있을 때 활용됨
componentDidUpdate(prevProps, prevState, snapshot)
리렌더링 이후 실행됨 앞의 두 파라미터를 통해서 컴포넌트가 이전에 가졌던 데이터에 접근할 수 있음
componentWillUnmount()
컴포넌트를 DOM에서 제거할 때 사용 componentDidMount에서 등록한 이벤트, 타이머 직접생산한 DOM이 있으면 여기서 제거 작업을 해야함
componentDidCatch()
컴포넌트 렌더링 도중에 에러가 발생했을 때 오류 UI를 보여줌
componentDidCatch(error, info) {
this.setState({
error: true
});
console.log({error, info});
}
***주의사항!!
컴포넌트 자신에게 발생하는 에러 잡을 수 없음 자신의 this.props.children으로 전달되는 컴포넌트에서 발생하는 에러만 잡아낼 수 있음
예시코드
import React, { Component } from 'react';
class ErrorBoundary extends Component {
state = {
error: false
}
componentDidCatch(error, info) {
this.setState({
error: true
});
console.log({error, info});
}
render() {
if(this.state.error) return <div>에러가 발생했습니다.</div>
return this.props.children;
}
}
export default ErrorBoundary;
App 예시코드
function getRandomColor() {
return '#' + Math.floor(Math.random() * 16777215).toString(16);
}
class App extends Component {
state = {
color: '#000000'
}
handleClick = () => {
this.setState({
color: getRandomColor()
})
}
render() {
return (
<div>
<button onClick={this.handleClick}>랜덤 색상</button>
<ErrorBoundary>
<LifeCycleSample color={this.state.color}/>
</ErrorBoundary>
</div>
)
}
}
export default App;