Skip to content

#30 [10장_1] 다음 쇼핑카트 컴포넌트에 타입스크립트를 적용하고 상태 관리로 useReducer를 사용하도록 바꿔주세요! #48

@drizzle96

Description

@drizzle96

❓문제

다음 쇼핑카트 컴포넌트에 타입스크립트를 적용하고 상태 관리로 useReducer를 사용하도록 바꿔주세요!

import { useState } from 'react'

const ShoppingCart = () => {
  const [cart, setCart] = useState({ items: [], total: 0 })

  const addItem = (item) => {
    setCart((prevCart) => {
      const newTotal = prevCart.total + item.price
      return {
        ...prevCart,
        items: [...prevCart.items, item],
        total: newTotal,
      }
    })
  }

  const removeItem = (index) => {
    setCart((prevCart) => {
      const itemPrice = prevCart.items[index].price
      const newItems = prevCart.items.filter((_, i) => i !== index)
      const newTotal = prevCart.total - itemPrice
      return {
        ...prevCart,
        items: newItems,
        total: newTotal,
      }
    })
  }

  return (
    <div>
      <h1>Shopping Cart</h1>
      <ul>
        {cart.items.map((item, index) => (
          <li key={index}>
            {item.name} - ${item.price}
            <button onClick={() => removeItem(index)}>Remove</button>
          </li>
        ))}
      </ul>
      <div>Total: ${cart.total}</div>
      <button onClick={() => addItem({ name: 'Apple', price: 1 })}>Add Apple</button>
    </div>
  )
}

export default ShoppingCart

🎯답변

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions