본문 바로가기
안드로이드 웹앱 콘테츠 개발자 양성(국비지원)/HybridApp

HybridApp-React Native 2세대 (기능 - Lifecycle Method)

by 차누감 2020. 1. 28.

<최종 화면>React Native의 Lifecycle에 대해 알아보자.

constructor() -> UNSAFE_componentWillMount() -> render() -> componentDidMount() - >

 ->componentDidUpdate() [화면 갱신될시 작동] -> componentWillUnmount() [컴포넌트 종료시 작동]

 

 


우선 AVD를 켜놓고 작업을 하자.

자신이 작업할 경로까지 접근하여 RN16Lifecycle을 만들자. 

코드를 작성하기 전에 우선 run을 하는 것이 좋다.

<실행 화면>화면에는 <Text>태그에 있는 글자만 보일 것이다. Lifecycle을 알기 위 log 확인해보자. 

방법 1. log 확인하는 방법 - 이미 run을 했을때 node창이 실행이 된다. node창을 보면 log가 나와 있다.

방법 2. 연결된 AVD에서 Ctrl+m을 누르자. 그러면 목록창이 뜨는데 Debug 를 누으면 웹페이지가 열린다. 

거기서 F12 개발자 모드로 해서 Console 탭을 보면 log를 확인할 수 있다.

log에는 4가지만 나왔다. didUpdate를 확인하기 위해 버튼을 만들어서 text 값을 변경해보자.

데이터가 변경되면 render()와 componentDidUpdate()가 실행된다.


<복붙용 코드>

Main.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
import React, {Component} from 'react';
import {View, Text, Button} from 'react-native';
 
export default class Main extends Component{
 
    state={text:"nice"};
    //라이프사이클 메소드
 
    //1.생성자
    constructor(){
        super();
        //화면에 보이기(render) 전에 실행되는 메소드이기에 화면에 출력 못함
        console.log('constructor!!!!'); //로그 찍기
    }
 
    // 2.화면에 보여지기 전에 자동 호출되는 콜백메소드(안드로이드의 onCreate()와 비슷)
    //componentWillMount(){ } //deprecate method.. 다른것 사용 
    UNSAFE_componentWillMount(){
        console.log('will constructor!!!!');
    } //권장하지 않음
 
    //3. 화면에 그려내는 메소드
    render(){
         console.log('render .........');
        return <View style={{padding:16}}>
                    <Text>{this.state.text}</Text>
                    <Button title="button" onPress={()=>{this.setState({text:"Hello"})}}></Button>
                </View>
    }
 
    // 4. 화면에 그려낸 후 딱 1번 호출되는 메소드
    componentDidMount(){
        // 보통 이 메소드 안에서 DB읽어오기나 네트워크로 데이터 불러오기 등의 작업 수행
        console.log('component did mount .........');
    }
 
    // 5. 화면이 갱신(re-render)될 때마다 호출되는 메소드
    componentDidUpdate(){
        console.log('component did update .........');
    }
 
    // 6. 이 컴포넌트가 종료될 때 자동 실행
    componentWillUnmount(){
        console.log('component will unmount !!!!');
    }
 
}
 

 

댓글