본문 바로가기

Frontend Study - 2/React

React : object, array 자료형의 응용

 

같은 위치에 표시되는 정보이지만 상태에 따라 다른 값들을 보여줘야 할 때가 있다.

예를들면 어떤 컴포넌트안에, 상태가 'order' 일 때는 주문정보들이 보여지고 'shipping'일 때는 배송정보, 'refund'일 때는 정산정보가 보여지게 하고 싶을 때.

뭔가 삼항연산자로 조건을 하나하나 주어야 할 것 같다. 하지만 객체 자료형의 응용을 통해 쉽게 구현할 수 있다.

 

function Component() {

	const [state, setState] = useState("order")
  
	return (
    <div>
      {
        {order : <p> order information </p>,
        shipping : <p> shipping information </p>,
        refund : <p> refund information </p>}[state]
      }
    </div>
  )
}

 

잘 이해가 가지 않는데, 아래 코드를 보면 더 이해가 잘 된다. 

 

const tapUI = {
	order : <p> order information </p>,
        shipping : <p> shipping information </p>,
        refund : <p> refund information </p>,
        }

function Component() {

	const [state, setState] = useState("order")
  
	return (
    <div>
      {
	tabUI[state]  
      }
    </div>
  )
}

tabUI[state] -> tapUI라는 객체 자료형에 [order] 라는 키로 값에 접근한 것이다. 현재 "order"라는 state가 default값으로 잡혀있기 때문에, 값에 해당하는 <p>order information</p>이 표시된다. setState를 통해 shipping, refund로 state값, 즉 key를 변경해 주면 그에 맞는 값을 볼 수 있다. 

array의 경우도 인덱스 값을 이용해서 접근하면 마찬가지로 응용할 수 있다.