-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
❓문제
다음 쇼핑카트 컴포넌트에 타입스크립트를 적용하고 상태 관리로 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🎯답변
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels