[React 주요 개념] 05. 라이프사이클 변경점
2022. 5. 14. 18:07ㆍ공부/React
React 16.3 버전 이상부터 몇몇 라이프 사이클이 변경됐다.
- componentWillMount -> getDerivedStateFromProps
- componentWillReceiveProps -> getDerivedStateFromProps
- componentWillUpdate -> getSnapshotBeforeUpdate
static getDerivedStateFromProps
특수한 경우에 사용되는 라이프사이클.
라이프사이클 앞부분에 꼭 static을 붙여주어야 하며, return 값이 존재해야 한다.
새로운 state를 설정하는 전용 라이프사이클로 변했다.
return 부분에 새로운 state를 선언할 수도 있다.
import React from 'react';
class App extends React.Component {
state = {
age: 0,
};
static getDerivedStateFromProps(nextProps, prevState) {
console.log(nextProps, prevState);
if (prevState.age !== nextProps.age) {
return { age: nextProps.age };
}
return null;
}
render() {
console.log('App render');
return <div>{this.state.age}</div>;
}
}
export default App;
getSnapshotBeforeUpdate
변한 값을 Update 되기 전에 가져오는 라이프사이클
import React from "react";
import "./App.css";
let i = 0;
export default class App extends React.Component {
state = { list: [] };
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevState.list.length === this.state.list.length) return null;
const list = document.querySelector("#list");
return list.scrollHeight - list.scrollTop;
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (snapshot === null) return;
const list = document.querySelector("#list");
list.scrollTop = list.scrollHeight - snapshot;
}
componentDidMount() {
setInterval(() => {
this.setState({
list: [...this.state.list, i++],
});
}, 1000);
}
render() {
return (
<div id="list" style={{ height: 100, overflow: "scroll" }}>
{this.state.list.map((i) => (
<div>{i}</div>
))}
</div>
);
}
}
getSnapshotBeforeUpdate의 return 값은 snapshot이라는 변수에 저장된다.
(props나 state가 변하지 않았다면 null로 비어있게 된다.)
'공부 > React' 카테고리의 다른 글
[React 주요 개념] 07. 조건부 렌더링 (0) | 2022.05.15 |
---|---|
[React 주요 개념] 06. Event Handling (0) | 2022.05.14 |
[React 주요 개념] 04. State와 Lifecycle (0) | 2022.05.14 |
[React 주요 개념] 03. Component와 Props (0) | 2022.05.14 |
[React 주요 개념] 02. 엘리먼트 렌더링, Virtual DOM (0) | 2022.05.14 |