이 글은 [리액트를 다루는 기술](저자 김민준, 출판사 길벗) 교재를 보고 공부하며 정리한 글임.
Will 접두사가 붙은 메서드는 어떤 작업을 작동하기 전에 실행되는 메서드
Did 접두사가 붙은 메서드는 어떤 작업을 작동한 후에 실행되는 메서드
------------------------
마운트:
DOM 이 생성되고 웹 브라우저 상에 나타나는 것
constructor : 컴포넌트를 새로 만들때마다 호출되는 클래스 생성자 메서드 입니다
getDerivedStateFromDrops: props에 있는 값을 state에 넣을 때 사용하는 메서드
render: 우리가 준비한 UI를 렌더링 하는 메서드
componentDidMount: 컴포넌트가 웹 브라우저상에 나타난 후 호출하는 메서드
-----------------------
업데이트:
props가 바뀔때
state가 바뀔때
부모 컴포넌트가 리렌더링될때
this.forceUpdate로 강제로 렌더링을 트리거할때
getDerivedStateFromProps: props의 변화에 따라 state값에도 변화를 주고 싶을때
shouldComponentUpdate: 컴포넌트가 리렌더링을 해야할지 말아야할지 결정하는 메서드
true혹은 false 반환
render:컴포넌트를 리렌더링합니다
getSnapshotBeforeUpdate:컴포넌트 변화를 DOM에 반영하기 직전 호출하는 메서드
componentDidUpdate:컴포넌트 업데이트 작업 끝나고 호출하는 메서드
------------------------
언마운트: 컴포넌트를 DOM에서 제거하는 것
componentWillUnmount:컴포넌트가 웹 브라우저 상에서 사라지기 전에 호출하는 메서드
LifeCycleSample.js
import React, {Component} from 'react';
class LifeCycleSample extends Component {
state = {
number : 0,
color : null,
}
myRef = null;
constructor(props){
super(props);
console.log('constructor');
}
static getDerivedStateFromProps(nextProps, prevState){
console.log('getDerivedStateFromProps');
if(nextProps.color !== prevState.color){
return {color: nextProps.color};
}
return null;
}
componentDidMount(){
console.log('componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('shouldCompoentUpdate', nextProps, nextState);
return nextState.number % 10 !== 4;
}
conponentWillUnmount(){
console.log('componentWillUnmount');
}
handleClick = () => {
this.setState({
number: this.state.number +1
});
}
getSnapshotBeforeUpdate(prevProps, prevState){
console.log('getSnapshotBeforeUpdate');
if(prevProps.color !== this.props.color){
return this.myRef.style.color;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log('componentDidUpdate', prevProps, prevState);
if(snapshot){
console.log('업데이트 되기 직전 색상', snapshot);
}
}
render(){
console.log('render');
const style={
color:this.props.color
};
return (
<div>
<h1 style={style} ref={ref => this.myRef=ref}>
{this.state.number}
</h1>
<p>color: {this.state.color}</p>
<button onClick={this.handleClick}>
더하기
</button>
</div>
)
}
}
export default LifeCycleSample;
App.js
import React, {Component} from 'react';
import LifeCycleSample from './LifeCycleSample';
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>
<LifeCycleSample color={this.state.color}/>
</div>
)
}
}
export default App;
에러잡아내기
ErrorBoundary.js
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.erro)return<div>에러가 발생했습니다!</div>;
return this.props.children;
}
}
export default ErrorBoundary;
App.js
import React, {Component} from 'react';
import LifeCycleSample from './LifeCycleSample';
import ErrorBoundary from './ErrorBoundary';
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;