React - Lifecycle

oceanzoo·2021년 6월 13일
0

Lifecycle

생성될 때 : rendering
constructor -> render -> componentDidMount
-> componentDidMount : 최초로 한번만 실행

업데이트할 때 : 상태가 변경될 때 (setState() , New props)
render -> componentDidUpdate

제거할 때: 라우터 이동시
componentWillUnmount

Lifecycle 순서

  1. constructor - 초기화
  2. render - 화면에 그려질 JSX를 정의하는 곳
  3. componentDidMount - ex) data fetching
  4. (fetch 완료)
  5. (setState)
  6. render
  7. componentDidUpdate (setState 되었기 때문에 컴포넌트 업데이트 발생)
  8. componentWillUnmount

자식 component 연관 있을 때
부모 constructor
부모 render
자식 constructor
자식 render
자식 componentDidMount
부모 componentDidMount

-> 즉 자식이 다 끝난뒤에 부모 componentDidMount 실행

여러 자식 component일 경우
부모 constructor
부모 render
자식 constructor
자식 render
자식 constructor
자식 render
자식 componentDidMount
자식 componentDidMount
부모 componentDidMount

조건부 렌더링

특정 조건일 때만 컴포넌트를 렌더링해야할 경우가 있다.

컴포넌트 함수 내부에서 특정 값에 따라 선택적으로 렌더링하는 것을 조건부 렌더링(conditional rendering)이라고 한다.

1) if문

render(){
	const {data} = this.state;
    	if(!data.message){
        	return null;
        }else{
        	return(
            	<div>
                {data.message.map((msg)=>{
                	return <li>{msg}</li>;
                })}
                </div>
            );
        }
 }

2) 삼항 연산자

return.data.message?null : (
	<div>
   	{data.message.map((msg))=>{
       	return <li> {msg} </li>;
        })}
   </div>
);

3) &&연산자

return(
	<div>
    	{data.message&& data.message.map(msg => {
        	return <li>{msg}</li>;
        })}
    </div>
);

&&연산자 사용 시 주의해야할 점!

  • 변수가 숫자 타입인 경우 0false 이다.
  • 변수가 문자열 타입인 경우 빈 문자열“”false이다.

true인 경우와 false인 경우

  • 객체들, 배열들, 0아닌 숫자값 : true
  • '', undefined, null, 0 : false

4)optional chaining

<div>
	{data.message?.map(msg=>{
    	return <li>{msg}</li>;
    })}
</div>

Lifecycle과 연관된 에러

해당 값이 어느 순간에는 비어있었다는 뜻이고, 상태값의 시점에 관한 문제라면 React의 Lifecycle과 연관이 있다.

profile
준비된 개발자를 위한 날갯짓 🦋

0개의 댓글