Code ReviewAdvanced~20 min

Review: State Management Issues

typescriptreactstate-managementhooks

Code Review Task

Please review the following React + TypeScript code.

Background

This is a component implementing shopping cart functionality. There are multiple issues with state management.

Review Criteria

  • State immutability
  • State update patterns
  • Utilizing useReducer
  • Derived state calculations

Your Answer

ShoppingCart.tsxtypescript
import React, { useState } from 'react';
interface CartItem {
id: number;
name: string;
price: number;
quantity: number;
}
function ShoppingCart() {
const [items, setItems] = useState<CartItem[]>([]);
const [totalPrice, setTotalPrice] = useState(0);
const addItem = (item: CartItem) => {
// Check for existing item
const existing = items.find(i => i.id === item.id);
if (existing) {
existing.quantity += item.quantity;
setItems(items);
} else {
items.push(item);
setItems(items);
}
// Update total price
setTotalPrice(totalPrice + item.price * item.quantity);
};
const removeItem = (id: number) => {
const index = items.findIndex(item => item.id === id);
if (index >= 0) {
const removedItem = items[index];
items.splice(index, 1);
setItems(items);
setTotalPrice(totalPrice - removedItem.price * removedItem.quantity);
}
};
return (
<div>
<h2>Shopping Cart</h2>
<p>Total: ${totalPrice}</p>
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} - ${item.price} × {item.quantity}
</li>
))}
</ul>
</div>
);
}
export default ShoppingCart;
行番号をクリックしてコメントを追加(Shift+クリックで範囲選択)

Minimum 100 characters required

0

Add comments and enter at least 100 characters in the summary

Model Answer

Submit your answer or click "Show" to view the model answer.