React 16 기초 Lifecycle - Updated (Class)
포스트
취소

React 16 기초 Lifecycle - Updated (Class)

componentDidUpdate

이는 클래스 컴포넌트에서 사용되는 라이프사이클중 하나로 이 메서드는 컴포넌트가 업데이트 된 직후에 호출됩니다 그렇다는 것은 주로 setState 로 인해서 state 변화로 인한 컴포넌트의 재 렌더링 하고 관련이 있을것입니다

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
import React from "react";

class Class_mount2 extends React.Component{

    constructor(props){
        super(props)

        console.log(1);
    }

    componentDidMount(){
        console.log(3)
    }

    componentDidUpdate(){
        console.log(4)
    }

    render(){
        console.log(2)
        return (
            
            <span>Class 형 컴포넌트 componentDidUpdate</span>
        )
    }

}

export default Class_mount2;

그럼 이에 대한 순서는 마찬가지로 constructor - > render -> componentDidMount 순으로 호출이 되지만 componentDidUpdate 는 호출이 되지 않습니다 이 함수의 특징은 props 나 state 변경으로 인해서 컴포넌트가 다시 렌더링 될때 호출되게 됩니다 그래서 제일 처음 화면을 불러오게 되면 이 함수는 호출되지 않습니다 그럼 state 를 변경해서 호출되도록 하겠습니다

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
import React from "react";

class Class_mount2 extends React.Component{

    constructor(props){
        super(props)

        console.log(1);

        this.state = {
            count : 1
        }
    }

    componentDidMount(){
        console.log(3)
    }

    componentDidUpdate(){
        console.log(4)
    }

    

    render(){

        const countUp = () => {
            this.setState((previous) => ({count : previous.count  + 1}))
        }

        const countDonw = () => {
            this.setState((previous) => ({count : previous.count - 1}))
        }


        console.log(2)
        return (
            <div>
                <span>Class 형 컴포넌트 componentDidUpdate</span>
                <span>클릭수 : {this.state.count}</span>
                <button onClick={countUp}>올리기</button>
                <button onClick={countDonw}>내리기</button>
            </div>
        )
    }

}

export default Class_mount2;

간단한 리액트 컴포넌트입니다 이때 버튼을 이용해서 state 를 변경하는 과정을 보게 됩니다 이렇게 되면 그제서야 componentDidUpdate 함수가 동작을 하게 됩니다 이때 호출되는것은 render -> componentDidUpdate 호출이 됩니다

댓글 등록을 이용한 componentDidUpdate 실습

이번에는 간단한 어플리케이션을 개발해서 댓글을 불러오고 댓글을 insert 하는 간단한 컴포넌트를 만들어보겠습니다

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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import React from "react";

class Class_mount3 extends React.Component{

    constructor(props){
        super(props)

        this.state = {
            commentList : []
        }
    }

    get_commentList = async() => {
        
        try{

            const reponse = await fetch('http://localhost:8080/v1/api/getCommentList' , {
                method : "GET" , 
                headers : {},

            }).then( (res) => {

                const status = res.status;
                if(status !== 200){

                    alert('서버와의 통신이 실패했습니다')

                }else{
                    return res.json();
                }

            }).then( (res2) => {

                this.setState({commentList : res2})

            })

        }catch(error){
            console.log(error)
        }
    }

    add_commentList = async() => {
        
        try{
            const paramData = this.state.commentList.filter(x => x.newComment === 'Y');

            if(paramData.length > 0){

                const response = await fetch("http://localhost:8080/v1/api/addCommentList" ,  {
                method : "POST" , 
                headers : {
                    "Content-Type": "application/json",
                } ,
                body :  JSON.stringify(paramData)
                     
                
            
            }).then( res => {

                const status = res.status;
                if(status !== 200){

                    alert('서버와의 통신이 실패했습니다')

                }else{
                    return res.json();
                }
            
            }).then( res2 => {
                this.get_commentList()
            })

            }
        }catch(error){
            console.log(error)
        }
    }

    commentaddEvent = () => {
        const name = document.querySelector("#input_id").value;
        const comment = document.querySelector("#input_comment").value;


        const newCommnetObject = {name : name , comment : comment , newComment : "Y"}
        const newCommentList = [...this.state.commentList , newCommnetObject]
        this.setState({commentList : newCommentList})

    }

    componentDidMount(){
        this.get_commentList();
    }

    componentDidUpdate(){
        this.add_commentList();
    }

    render(){

        return (
            <div>
                <div>
                {
                    this.state.commentList.map(x => {
                        
                        return (
                            <div>
                                <span>name : {x.name}</span>
                                <span>comment : {x.comment}</span>
                            </div>
                        )
                    })
                }
                </div>
                <div>
                name : <input id = "input_id" type="text"/>
                comment : <input id = "input_comment" type="text"/>
                <button onClick={this.commentaddEvent}>댓글 작성</button>
                </div>
            </div>
        )
    }
}

export default Class_mount3;

다소 복잡해졌지만 함수를 하나하나 따라가보자

  1. this.state = {commentList : [] } 에서는 우리가 상태를 관리할 변수를 선언을 해두었습니다

  2. get_commentList 는 함수로 서버로 가서 commentList 를 가져와서 state 에 set 을 하는 api 입니다

  3. add_commentList 는 하단에 버튼을 이용해서 댓글을 입력하면 그 중 신규 댓글만 가져와서 서버에 insert 를 치는 방식입니다

  4. commentaddEvent 는 하단에 버튼 클릭에 대한 이벤트로 클릭시 기존의 state 와 지금 입력된 데이터를 바탕으로 스프레드 배열로 완전 새로운 배열을 만들어서 setState 하는 과정입니다

  5. componentDidMount 는 컴포넌트 생성시 commetList 를 가져오는 api 를 호출하게 합니다

  6. componentDidUpdate 는 컴포넌트 버튼을 이용한 댓글 입력시 state 가 변경되는데 이때 변경된 데이터를 가져와서 api 호출로 서버에 데이터를 입력후 this.get_commentList() 를 통해서 다시 한번 데이터를 렌더링 하는 과정을 담았습니다

우리는 이렇게 state 가 변경이 되면 자동으로 호출되는 componentDidUpdate 에 대해서 살펴보았습니다 다음장에서는 같은 내용을 함수형 컴포넌트에서는 어떻게 사용하는지에 대해서 알아보도록 하겠습니다