const 컴포넌트 = () => {
if(true){
return <div>짠</div>
} else{
return null
}
}
자주쓰는 간단한 if문
const 컴포넌트 = () => {
return (
<div>
{
1 === 1
? <p>짜잔</p>
: null
}
</div>
)
}
물론 삼항연산자는 중첩사용도 가능하나 그렇게 쓸꺼면 다른 방식으로 작성합시다.
if문 쓸 때 만약 참이면 ~이거보여주고 아니면 null해주셈 할 때 삼항연산자 대신 보기 좋게 &&연산자 사용 추천
const 컴포넌트 = () => {
return (
<div>
{
1 === 1 && <p>짜잔</p>
}
</div>
)
}
이경우 조건식이 true일 때 보일 값을 작성만 해주면 끝!
if문을 연달아 많이 사용할때 사용하여 코드를 줄 일 수 있습니다
예시로 redux reducer쓸 때 생각해보면
function reducer(state, action){
if (action.type === 'addProuduct'){
return addState
} else if (action.type === 'removeProduct'){
return removeState
} else {
return state
}
}
이렇게 쓸 껄
function reducer(state, action){
switch (action.type) {
case 'addProduct' :
return addState;
case 'removeProduct' :
return removeState;
default :
return state
}
}
이렇게 사용 가능
사용법은
1)switch (검사할변수명){} 작성
2)case 검사할변수명이 일치하는지 : 작성
3)일치시 case 밑에 코드 실행
4)default : 는 맨 마지막 else문과 동일
경우에 따라서 다른 HTML을 보여주고 싶은 경우 사용
const 컴포넌트 = () => {
const [current, setCurrent] = useState('info');
return (
<div>
{
{
info : <p>정보</p>,
shopping : <p>쇼핑</p>,
refund : <p>환불</p>
}[current]
}
</div>
)
}
예시로 이런 경우가 있다면 지금 예시는
objec{} 뒤에 [] 대괄호를 붙여서 "key값이 current인 자료를 보여주세요"라고 나타내고 있습니다
이런 경우 current라는 state값을 변경 시키는 것만으로 원하는 HTML을 보여줄 수 있습니다. 좀 더 코드를 깔끔히 정리하면
let innerText = {
info : <p>정보</p>,
shopping : <p>쇼핑</p>,
refund : <p>환불</p>
}
const 컴포넌트 = () => {
const [current, setCurrent] = useState('info');
return (
<div>
{
innerText[current]
}
</div>
)
}
이렇게 축약 가능합니다