[React] States

호두파파·2021년 5월 12일
0

React

목록 보기
19/38

States

상황에 따라 가변적인 정보와 UI가 연관될 수 있다. 이런 가변적인 정보를 상태라 부르고, 이 상태를 관리할 수 있는 방법이 바로 state이다.

export default function ShoppingItem (props) {
  const {
    name,
    price
  } = props.item

  return (
    <div>
      <h3>{name}</h3>
      <h4>{price}</h4>
      <div>
        <div>-</div>
        <div>1</div>
        <div>+</div>
      </div>
    </div>
  )
}

사용자가 더하기, 빼기 버튼을 클릭할때마다 우리는 수량의 값을 변경시켜 UI에 반영하고 싶다. 이와 같은 상황에서 우리는 useState라는 함수를 이용해 수량을 가변적인 상태값으로 관리할 수 있다. useState를 적용해 초기 수량을 1로 표기하기 위해 아래와 같이 수정할 수 있다.

export default function shoppingItem (props) {
  const {
    name, 
    price
  } = props.item
  const [quantity, setQuantity] = useState(1)
  
  return (
    <div>
      <h3>{name}</h3>
      <h4>{price}</h4>
      <div>
        <div>-</div>
        <div>{quantity}</div>
        <div>+</div>
      </div>
    </div>
   )
  )

사용자와 더하기, 빼기 버튼을 클릭할때마다 해당 수량을 변경하는 코드를 추가해보면 아래와 같다.

export default function ShoppingItem (props) {
  const {
    name,
    price
  } = props.item
  const [quantity, setQuantity] = useState(1)
  
  function changeQuantity(qty) {
    if (quantity <= 0) {
      return
    }
    setQuantity(quantity + qty)
  }
  return (
    <div>
      <h3>{name}</h3>
      <h4>{price}</h4>
      <div>
        <div onClick={() => changeQuantity(-1)}>-</div>
        <div>{quantity}</div>
        <div onClick={() => changeQuantity(1)}>+</div>
      </div>
    </div>
  )
}

이제 우리가 원하는 만큼 다양한 state값을 만들어 사용할 수 있다. 아래 코드에서는 && 연산자를 이용해 조건에 따라 보여주거나 숨겨주는 로직을 작성했다.

export default function ShoppingItem (props) {
  const {
    name,
    price
  } = props.item
  const [quantity, setQuantity] = useState(1)
  
  function changeQuantity(qty) {
    if (quantity <= 0) {
      return
    }
    setQuantity(quantity + qty)
  }
  return (
    <div>
      <h3>{name}</h3>
      <h4>{price}</h4>
      <div>
        <div onClick={() => changeQuantity(-1)}>-</div>
        <div>{quantity}</div>
        <div onClick={() => changeQuantity(1)}>+</div>
      </div>
      {error && (
        <p>{error}</p>
      )}
    </div>
  )
}
profile
안녕하세요 주니어 프론트엔드 개발자 양윤성입니다.

0개의 댓글