life cycle

Steve·2021년 10월 17일
0
  1. 컴포넌트 라이프 사이클 각 단계를 나의 위스타그램 작업물을 예시로 들어 설명할수있다.
  2. 부모 자식 관계 컴포넌트에서 라이프 사이클이 어떤 순서로 호출되는지 설명할수있다
  3. 데이터 호출 과정에서 발생하는 can not read property of undefined error 의 원인을 설명할 수 있다.
  4. 위 에러를 조건부 렌더링으로 해결할 수 있다.
  5. 자바스크립트 각 데이터타입의 truty/ falsy를 설명할 수 있다.
    컴디마(딱 1회만 시행됨): fetch, eventlistener를 달아줌.
    컴디업, 컴윌언마운트

다 그려졌다는 전제하에, 이제 다그려졌으니까 더가져오려면 가져오라는 명령어
컴디마.
*render나 constructor에서는 DOM에 접근 불가!
이유는?
화면에 아직 그려지지 않았기 때문. 완료가 안돼서.
실제로 화면에 그려져야 그 DOM에 접근가능하다.
컴디마 이전까지는 DOM이 아직 없는 상태.

render가 다시 불리는경우 2가지
1. New props
2. setState()

render(){ //UI를 리턴함
}


parent plus 클릭시,

parent setstate
parent render
child render
child comdiup
parent comdiup

child plus 클릭시,
child setState
child render
child comdiup



그렇다. 비동기 데이터 처리할 때는 값이 비어있을때의 예외처리를 해줘야 한다.

import React, { Component } from "react";

export default class FetchError extends Component {
 constructor() {
   super();
   this.state = {
     data: {},
   };
 }

 componentDidMount() {
   fetch("/lifecycle.json")
     .then((res) => res.json())
     .then((res) => {
       this.setState({ data: res });
     });
 }

 render() {
   console.log(this.state.data);
   return (
     <div>
       {this.state.data.message // 값이 아직 안들어왔을때를 확인하기 위함
         ? this.state.data.message.map((msg, idx) => {
             return <li key={idx}>{msg}</li>;
           })
         : null}
     </div>
   );
 }
}

constructor 안에 data: {}로 돼있으면 조건부렌더링으로 비어있을때 를 처리해줘야함.
하지만 data : { message:[] }
*위를 더 간단히 처리
-> {this.state.data.message // 이게 true일때만 뒤의것을 평가하겠다.
&& this.state.data.message.map((msg, idx) => {
return

  • {msg}
  • ;
    })}

    null 쓰는거 귀찮자나 위처럼 써라.
    구조 분해할당도 제발좀 하자

    Boolean(""); //false
    Boolean([]); //true
    Boolean([1, 2, 3]); //true
    Boolean({}); //true
    Boolean({ a: 1 }); //true

    배열과 객체는 참조형 데이터이기 때문에 true로 판별

     const state = {
    	arr : [] //0
    }
    { this.state.arr.length > 0 && this.state.arr.map( () = > {} ) }// 배열의 길이가 유효할때 render하겠다.(map을 돌리겠다)
    { !!this.state.arr.length && this.state.arr.map( () = > {} ) } //위랑 같은 뜻
    { this.state.arr.map( () = > {} ) } // 이렇게 해도 에러 안뜸
    profile
    Front-Dev

    0개의 댓글