React에서 생명주기란
comopnent의 생성, 변경, 소멸 과정을 뜻한다.
변경
- shouldComponentUpdate()
shouldComponentUpdate()
- component의 ‘변경’과정에 속한다.
-‘변경’이란 porps나 state의 변경을 말한다.
-componentDidMount() 함수는 ‘생성’ 단계의 생명주기 함수 중 가장 마지막으로 실행된다.
-tmp_state2라는 state 변수에 true라는 boolean 유형의 데이터를 세팅했다.
-setState() 함수는 변수의 선언과 초기화를 동시에 실행한다.
-line18에서 state의 변경이 발생했기 때문에 ‘변경’ 단계의 생명주기 함수 shouldComponentUpdate()가 실행된다.
-shouldComponentUpdate()는 boolean 유형의 데이터를 반환하는데, return값이 true일 경우에 render() 함수를 한 번 더 호출한다.
-shouldComponentUpdate() 함수의 반환 값에 따라 render() 함수를 재실행할 수 있다는 점을 이용하면, props나 state 변수가 변경될 때 화면을 다시 그리며 제어할 수 있다.
예제코드
App.js
import React from 'react';
import './App.css';
import LifecycleEx from './R008_LifecycleEx';
function App() {
return (
<div>
<h1>Start React 200!</h1>
<p>css 적용하기</p>
<LifecycleEx prop_value = 'FromApp.js'/>
</div>
);
}
export default App;
R008_LifecycleEx.js
import React, { Component } from "react";
class R008_LifecycleEx extends Component {
static getDerivedStateFromProps(props, state){
console.log('2. getDerivedStateFromProps Call : '+props.prop_value);
return {tmp_state:props.prop_value};
}
constructor(props) {
super(props);
this.state={};
console.log('1. constructor Call');
}
componentDidMount(){
console.log('4. componentDidMount Call');
console.log('5. tmp_state : '+this.state.tmp_state);
this.setState({tmp_state2 : true});
}
shouldComponentUpdate(props, state){
console.log('6. shouldComponentUpdate Call / tmp_state2 = '+state.tmp_state2);
return state.tmp_state2;
}
render() {
console.log('3. render Call');
return (
<h2> [THIS IS shouldComponentUpdate FUNCTION] </h2>
)
}
}
export default R008_LifecycleEx;
실행결과
'FrontEnd > React.js' 카테고리의 다른 글
class 사용하기 (0) | 2022.06.26 |
---|---|
전개 연산자 사용하기 (0) | 2022.06.26 |
React의 생명주기-생성 (0) | 2022.06.23 |
React의 기본 구조 (0) | 2022.06.23 |
React.js (0) | 2022.06.22 |