//LifeCycleSample.js
import React, { Component } from 'react';
class LifeCycleSample extends Component {
state = {
number: 0,
color: null,
}
myRef: null; //ref 를 설정할 부분
constructor(props){
super(props);
console.log('constructor');
}
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.color !== prevState.color){ //조건에 따라 값 동기화
return { color: nextProps.color };
}
return null; //state 를 변경할 필요가 없다면 null 값을 반환
}
componentDidMount(){
console.log('componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('shoudComponentUpdate', nextProps, nextState);
return nextState.number %10 !== 4; //새로 설정될 number 값의 마지막 숫자가 4이면 업데이트 하지 않는다-> return 값은 true, false !!
}
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');
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;
'Front-End > React.js' 카테고리의 다른 글
React Life Cycle API (0) | 2022.05.01 |
---|---|
React arrow fucntion (0) | 2022.05.01 |
React 이벤트 핸들링 (0) | 2022.05.01 |
[리액트를 다루는 기술] 3장. props, state (0) | 2022.05.01 |
[리액트를 다루는 기술] 1,2장. JSX (0) | 2022.05.01 |