component Lifecycle
리액트 컴포넌트는 탄생부터 죽음까지 여러지점에서 개발자가 작업이 가능하도록 메서드를 오버라이딩 할 수 있게 해준다.
component 라이프사이클 (< v16.3)
Declarative
여러가지 탄생부터 죽음까지 순간순간을 선언적으로 표현해 놓으면, 선언 적으로 표현된 함수들을 실행할 수 있게 해주기 때문에 효과적으로 처리할 수 있다.
initialization ⇒ 컨스트럭터가 불리면서 초기값이 세팅되는 것, 처음으로 그려진다.
constructor : 생성되는 순간 (인스턴스화)
mounting ⇒ 렌더 직전, 렌더링, 렌더 직후
componentWillMount
render(최초 랜더)
componetDidMount
Updation ⇒ props 와 states
변경되서 랜더가 재 진행될때
shouldComponentUpadate (true, false)
할지 말지 결정해 주는 부분 ⇒ 조건부로 막아 놓는다면 랜더가 되는 것을 효율적으로 관리 할 수 있음. (불필요하게 랜더되는것을 방지할때 도움, 리액트 성능 최적화 할때 중요한 역할)
componentWillReceiveProps
- props 를 새로 지정했을 때 바로 호출됩니다.
- 여기는 state의 변경에 반응하지 않습니다.
- 여기서 props의 값에 따라 state를 변경해야 한다면, setState를 이용해 state를 변경합니다. 그러면 다음 이벤트로 각각 가는것이 아니라 한번에 변경됩니다.
shouldComponentUpdate
- props 만 변경되어도
- state 만 변경되어도
- props & state 둘다 변경되어도
- newProps 와 newState 를 인자로 해서 호출
- return type 이 boolean 입니다.
- true 면 render
- false 면 render 가 호출되지 않습니다.
- 이 함수를 구현하지 않으면, 디폴트는 true
componentWillUpdate
- 컴포넌트가 재 랜더링 되기 직전에 불립니다.
- 여기선 setState 같은 것을 쓰면 아니됩니다.
render
componentDidUpdate
- 컴포넌트가 재 랜더링을 마치면 불립니다.
unmounting ⇒ 화면에서 사라지는 부분 , 사라지기 직전 componentWillUnmount
class App extends React.Componet {
state = {
age ; 39,
}
interval = null;
constructor(props){
super(props);
console.log('constructor', props);
}
render(){
console.log('render')
return(
<div>
<h2>
Hello {this.props.name} - {this.state.age}
</h2>
</div>
);
}
//componentWillMount(){
// console.log("componentWillMount")
//}
static getDerivedStateFromProps(nextProps, prevState){
console.log('getDerivedStateFromProps',nextProps, prevState)
//새로운 props 가 들어왔을때 state 도 변경가능,
//(16.3 변경 이후) 랜더가 실행되기 전에 무조건 불린다! state가 변경되어도 불림
return {
age : 29,
};
}
componentDidMount(){
console.log("componentDidMount");
this.interval = setInterval(()=>{
console.log("setInterval");
this.setSate(state)=> ({ ...state, age: state.age + 1});
},1000);
}
//componentWillReceiveProps(nextProps){
// console.log('componentWillReceiveProps', nextProps);
//}
shouldComponentUpdate(nextProps,nextState){
console.log('shouldComponentUpdate', nextProps, nextState)
// 조건부로 랜더링 되는 것을 막을 수 있어 >> 효율적으로 관리
return false;
}
//componetWillUpdate(nextProps,nextState){
// console.log('componetWillUpdate',nextProps,nextState);
//};
componentDidUpdate(prevProps,prevState){
consoel.log('componentDidUpdate',prevProps,prevState);
}
componentWillUnmount(){
celarInterval(this.interval)
}
}
ReactDOM.render(<App name="Mark" />,
document.querSelector("#root"),
);
let i =0;
class App extends React.Componet {
state = {list : []};
render() {
return (
<div id = "list" style ={{height:100, overflow: 'scroll'}} >
{this.state.list.map(i =>
{return <div>{i}</div>;
})}
</div>
)
componentDidMount(){
setInterval(()=> {
this.setState(state => ({
list : [...state.list, i++]
}));
},1000);
}
getSnapshotBeforeUpdate(prevProps,prevState){
if(prevState.list.length === this.state.list.length) return null;
const list = document.querSelector('#list');
return list.scrollHeight - list.scrollTop;
}
componentDidUpdate(prevProps, prevState, snapshot){
console.log(snapshot);
if(snpashot === null) return;
const list = document.querSelector('#list');
list.scrollTop = list.scrollHeight - snanpshot;
}
}
}
component 라이프사이클 (v16.3)
constructor
componentWillMount ⇒ getDerivedtateFromProps
render
componentDidMount
componenWillReceiveProps ⇒ getDerivedStateFromPops
shouldComponentUpdate
render
componenWillUpdate ⇒ getSnapshotBeforeUpdate (dom에 적용)
componentDidUpdate
componentWillUnmount
Componet 에러 캐치
class App extneds React.Component {
state = {
hasError : fasle;
}
render(){
if(this.state.hasError){
reutrn <div>예상치 못한 에러가 발생</div>
}
return (<WebService / >;)
}
componentDidCatch(error, info) {
this.setState({hasError : true});
}
}
Error Boundaries
- 가장 최상위에 있어야 밑에서 발생하는 에러를 잡아서 처리할 수 있습니다.
'FRONTEND > React' 카테고리의 다른 글
[react] 회원가입 폼 만들기 #3 - react-hook-form 라이브러리 (0) | 2023.02.08 |
---|---|
[react] 회원가입 폼 만들기 #2 - 반복되는 코드 합치기 그리고 한계 (0) | 2023.02.07 |
[react] 회원가입 폼 만들기 #1 - 기본 구조와 유효성 검사 세팅 (0) | 2023.02.06 |
[React] React Component 흐름도 (0) | 2022.06.02 |
[React] CSR vs SSR 차이는? (0) | 2022.06.02 |