컴포넌트를 이용해 필요한 부분만 새로 렌더하다보면 순서에 맞지 않는 코드로 인해 Lifecycle 관련 에러가 나온다.
기본적으로 컴퓨터는 위에서 아래로 코드를 읽어나가기 때문에 컴포넌트의 Lifecycle을 늘 신경쓰고 때에 따라 조건부 렌더링을 설정해주어야 한다.
constructor
render
–
componentDidMount
fetch 완료
render
setState
–
componentDidUpdate
setState로 인한 컴포넌트 업데이트 발생
componentWillUnmount
부모의 render 안에 있는 자식 컴포넌트는 내부에서 부모보다 한 단계 더 먼저
부모 constructor
부모 render
–
1. 자식 constructor
2. 자식 render
3. 자식 componentDidMount - componentDidMount 이후에 render 없이 부모 컴포넌트로 이동
–
부모 componentDidMount (fetch 완료)
setState 발생 -> 업데이트 발생 -> 다시 render
부모 render
–
4. 자식 render
5. 자식 componentDidUpdate - componentDidMount는 최초 렌더 시 한번만 실행되기 때문에 componentDidUpdate로 발생
–
5. 부모 componentDidUpdate
특정 조건에 해당하는 경우에만 렌더하는 것이 바로 조건부 렌더링이다. return문 안에서 JSX에 인라인으로 사용 가능한 여러 방법이 있으므로 함께 소개해보려 한다.
논리연산자 A && B
A가 true일 경우 B를 렌더한다.
삼항연산자 A ? B : C
A가 true일 경우 B, 아닐 경우 C를 렌더한다.