실습에 앞서 LifeCycleSample.js파일을 생성합시다.
LifeCycleSample.js
// LifeCycleSample.js
import React, { Component } from 'react';
class LifeCycleSample extends Component {
state = {
number: 0,
color:null
}
myRef = null; //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('shouldComponentUpdate', nextProps, nextState);
// 숫자의 마지막 자리가 4면 리렌더링 하지 않습니다
return nextState.number % 10 !== 4;
}
componentWillUnmount(){
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
- App.js
```jsx
// App.js
import { 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;
렌더링이 잘된걸 확인하셨다면, 이제 오류를 발생시켜 봅시다.
// LifeCycleSample.js
...
render() {
console.log('render');
const style = {
color: this.props.color
}
return (
<div>
{this.props.missing.value} {/* 오류를 발생시킵니다. */}
<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;
오류가 발생한걸 볼 수 있습니다.
ErrorBoundary.js 파일 생성
// 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.error)
return (
<div>
에러가 발생했습니다!
</div>
);
return this.props.children;
}
}
export default ErrorBoundary;
App.js파일 수정
// App.js
import { 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>
<ErrorBoundary>
<button onClick={this.handleClick}>랜덤색상</button>
<LifeCycleSample color={this.state.color}/>
</ErrorBoundary>
</div>
);
}
}
export default App;
이런식으로 오류가 발생했을 시 원하는 메세지를 출력할 수 있습니다.