본문 바로가기
React

Component 의 LifeCycle 예제

by 정정훈의 아날로그 2021. 4. 22.

책보고 예제를 만들어보긴했는데 아직 완벽하게 숙지되지는 않는다.

console 창을 켜놓고 계속 클릭 + 소스 분석을 더 해봐야 숙지할수있을것 같다.

 

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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;
cs

LifeCycleSample.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
import React, { Component, Componet } from "react";
 
class LifeCycleSample extends Component {
  state = {
    number: 0,
    color: null,
  };
 
  myRef = null;
 
  constructor(props) {
    super(props);
    console.log("constructor");
  }
 
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.color !== prevState.color) {
      return { color: nextProps.color };
    }
    return null;
  }
 
  componentDidMount() {
    console.log("componentDidMount");
  }
 
  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponent", 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;
 
cs

 

shouldComponentUpdate() 매서드에 대한 이해가 부족한것같다.

책에서도 shouldComponentUpdate() 를 사용하는법을 더 다룬다고 하니 이해가 되면 관련 포스팅을 추가하겠다.

'React' 카테고리의 다른 글

map()과 filter() 의 차이  (0) 2021.04.28
shouldComponentUpdate 메서드  (0) 2021.04.22
Component 의 LifeCycle  (0) 2021.04.22
map() + @  (0) 2021.04.21
Component 에 ref 설정하기  (0) 2021.04.20