Cart Management
React 购物车状态管理:重复预防、localStorage 持久性、CartContext 模式。在构建或修复购物车、产品列表或与购物车相关的 UI 时使用。
安装 / 下载方式
TotalClaw CLI推荐
totalclaw install totalclaw:konscious0beast~konscious0beast-cart-managementcURL直接下载,无需登录
curl -fsSL https://skills.taituai.com/api/skills/totalclaw%3Akonscious0beast~konscious0beast-cart-management/file -o konscious0beast-cart-management.mdGit 仓库获取源码
git clone https://github.com/openclaw/skills/commit/cf648287213030a557e7e85ee80701dde31744d8## 概述(中文)
React 购物车状态管理:重复预防、localStorage 持久性、CartContext 模式。在构建或修复购物车、产品列表或与购物车相关的 UI 时使用。
## 原文
# Cart Management Skill
Patterns for React cart state: duplicate prevention, persistence, context design.
## Duplicate Prevention
- Track product IDs in CartContext (separate state or derived from cartItems)
- Check `productIdsInCart.includes(item.id)` before add
- Centralize logic in context, not in ProductCard or child components
## Persistence (localStorage)
- Initialize cart state from `localStorage.getItem('cart')` on mount
- Persist on every add/remove: `localStorage.setItem('cart', JSON.stringify(cartItems))`
- Sync productIdsInCart if used: `localStorage.setItem('cart_ids', JSON.stringify(ids))`
- Prevents duplicates across sessions (refresh, new tab)
## CartContext Pattern
```tsx
const addToCart = (item: CartItem) => {
if (!productIdsInCart.includes(item.id)) {
setCartItems(prev => [...prev, item]);
setProductIdsInCart(prev => [...prev, item.id]);
localStorage.setItem('cart', JSON.stringify([...cartItems, item]));
}
};
```
## Anti-Patterns
- Don't add to cart in useEffect on ProductCard mount (causes duplicates)
- Don't duplicate logic in multiple components – use context
- Add backend validation as fallback for data integrity
## Quantity Updates
For same-product quantity: use `cartItems.map()` to update item.quantity, don't create duplicate entries.