지난 편(React Native App 개발기 6-1)에서 알아본 컴포넌트 생명주기에 대해서 코드로 알아보려 한다.
아래의 설명한 사항은 React Version 16.4를 기준으로 동작하는 함수 및 절차이다.
React Native 메인

- Component의 생명 주기를 알아보기 위해서 Main Component를 Import하여 아래와 같이 사용하였다.
- React Hook의 useState를 이용해서 함수 내에서 state를 사용하여 상태를 Main Component로 전달하였다.
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, { useState } from 'react';
import { View, Text, Button } from 'react-native';
import Main from './src/pages/Main';
import ErrorBoundary from './src/pages/Error'
const App = () => {
const [ value, setValue ] = useState({ data : "" });
const onPressEvent = () => {
setValue({ data : "11" });
}
return (
<>
<ErrorBoundary>
<View style={{ flex : 1, justifyContent : 'center', alignItems:'center' }} >
<Text>Component Life Cycle 입니다.</Text>
<Button title="클릭" onPress={onPressEvent} ></Button>
</View>
<Main stateProps={value} propsData={11} />
</ErrorBoundary>
</>
);
};
export default App;
React Native ErrorBoundary
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
}
static getDerivedStateFromError(){
console.log("getDerivedStateFromError");
}
render() {
return this.props.children;
}
}
export default ErrorBoundary;
React Native Main
- Component Lifecycle에 활용되는 모든 함수를 아래와 같이 정의하여 Component 호출 시점, Props 전달 시점, State 전달 시점을 알아보려한다.
- 각각의 함수에 console.log를 추가하여 호출 시점을 알아보겠다.
import React, { Component } from 'react';
import {
View,
Text,
} from 'react-native';
class Main extends Component{
constructor(props){
super(props);
console.log("constructor");
}
static getDerivedStateFromProps(props, state){
console.log("getDerivedStateFromProps") ;
}
shouldComponentUpdate(nextProps, nextState){
console.log("shouldComponentUpdate");
}
getSnapshotBeforeUpdate(prevProps, prevState){
console.log("getSnapshotBeforUpdate");
}
componentDidMount(){
console.log("componentDidMount");
}
componentWillUnmount(){
console.log("componentWillUnmount");
}
render(){
return (
<View style={{flex : 1, justifyContent : 'center', alignItems:'center' }} >
<Text>Component 입니다.</Text>
</View>
)
}
}
export default Main;
- 메인화면이 호출될 때, ( command + R 을 눌러 메인화면을 새로고침 했다. )

호출 순서 : constructor -> getDerivedStateFromProps -> componentDidMount
- 메인화면에서 버튼을 클릭했을 때, ( React Hook을 이용해 state를 component로 전달했다. )

호출 순서 : getDerivedStateFromProps -> shouldComponentUpdate
- 메인화면에서 다른 화면으로 전환될 때
호출 순서 : componentWillUnmount
- ErrorBoundary를 감싸고 있는 하위 컴포넌트에서 에러가 발생했을 때,
호출 순서 : getDerivedStateFromError
Mounting에서 부터 Unmounting 까지의 절차는 아래의 Link에서 가져온 이미지에서 잘 정리되어 있었다.

다음편에서 16.3 기점으로 나뉜 컴포넌트 생명주기 함수들에 대해서 자세히 설명할 예정이다.
'따라해보기' 카테고리의 다른 글
| 0001 React Native App 개발기 7 (0) | 2019.12.14 |
|---|---|
| 0001 React Native App 개발기 6-3 (0) | 2019.12.13 |
| 0001 React Native App 개발기 6-1 (0) | 2019.12.12 |
| 0001 React Native App 개발기 5 (0) | 2019.12.08 |
| 0001 React Native App 개발기 4 (0) | 2019.11.22 |