Wecode 36일차

김상연·2021년 3월 28일
0

wecode

목록 보기
36/42

LifeCycl의 기본 순서

  1. constructor
  2. render
  3. componentDidMount
  4. (fetch 완료)
  5. render
  6. (setState)
  7. componentDidUpdate (setState 되었기 때문에 컴포넌트 업데이트 발생)
  8. componentWillUnmount

특정 조건에서만 컴포넌트를 렌더링해야 하는 상황이 발생
그럴 때는 컴포넌트 특정 값에 따라 선택적으로 렌더링하는 것을 조건부 렌더링이라고 함.

조건부 렌더링을 구현할 때는 삼항연산자도 유용하지만 && 연산자가 가독성이 더 좋음.

class Greetin extends Component {
	render() {
		const { isLogin, name, point } = this.props;
		return {
			<div>
				{isLogin ? (
					<div>
						<p>{name}님 환영합니다!</p>
						<p>현재 보유중인 포인트는 {point}원 입니다.</p>
					</div>
				) : null}
			</div>
	}
}

위 코드와 같이 작성하면 false경우의 값을 할당해야해서 null을 입력한다.

class Greetin extends Component {
	render() {
		const { isLogin, name, point } = this.props;
		return {
			<div>
				{isLogin && (
					<div>
						<p>{name}님 환영합니다!</p>
						<p>현재 보유중인 포인트는 {point}원 입니다.</p>
					</div>
				)}
			</div>
	}
}

하지만 위와 같이 && 연산자를 이용하여 작성하면 null이 생략되어 가독성이 더 좋아진다.

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

  • 변수가 숫자 타입인 경우 0은 false

  • 변수가 문자 타입인 경우 ""도 false

LifeCycle에 관련된 에러

가끔 map함수를 실행할 떄 위와 같은 에러 메시지를 접할 수 있다. 이럴 때는 해당 값이 어느 순간부터 비어있었다는 뜻이고 LifeCycle에 연관이 있는 것이다.

0개의 댓글