하루 30분 TIL
221025 TIL
devSoo
2022. 10. 26. 00:58
1. 렌더링 조건문에서 && 보다 삼항연산자를 쓰는 게 낫다.
🔴 BAD
condition && <ConditionalComponent />🟢 GOOD
condition ? <ConditionalComponent /> : null
이유는 조건이 0이라면 0이 UI에 뜰 것이고 undefined이라면 아래와 같은 에러가 뜰 것이다.
- if condition is 0, 0 is displayed in the UI
- if condition is undefined, you’ll get an error: "Uncaught Error: Error(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null."
실제로 예전에 아래와 같은 코드를 서비스에 써서 0이 노출된 경험이 있다.
productsToPay.orderArr.length && (
<ProductToOrder
isGiftOrder={isGiftOrder}
isComplete={true}
orderLists={productsToPay.orderArr}
totalPrice={totalProductPrice + totalDeliveryPrice}
/>
)
하지만 condition이 확실히 boolean을 보증할 때는 && 연산자를 쓰는게 낫지 않을까 싶다.
참고자료
2. 선언적 프로그래밍 vs 명령적 프로그래밍
선언적프로그래밍 : 무엇을 할 지 알려줘, 세부구현은 미리 해놨거든
명령형프로그래밍: 어떻게 해야할 지 하나하나 명령하기
참고자료