fix(shop): 购物车页面进入不刷新问题

- 购物车页面添加 useDidShow 钩子,页面显示时自动刷新购物车数据
- 商品列表页和分类页改用 CartContext 的 addItem 方法添加商品
- 移除直接调用 addToCart API,避免购物车状态不同步
- 解决从商品列表页或分类页加入购物车后进入购物车页面商品不显示的问题
This commit is contained in:
2026-07-14 02:25:12 +08:00
parent 7a14272fe8
commit b8d2325ff9
4 changed files with 27 additions and 20 deletions

View File

@@ -3,7 +3,7 @@ import { View, Text, ScrollView, Image, Input } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { listShopGoodsCategory } from '@/api/shop/shopGoodsCategory'
import { pageShopGoods } from '@/api/shop/shopGoods'
import { addToCart } from '@/api/shop/shopCart'
import { useCartContext } from '@/contexts/CartContext'
import type { ShopGoodsCategory } from '@/api/shop/shopGoodsCategory/model'
import type { ShopGoods, ShopGoodsParam } from '@/api/shop/shopGoods/model'
import { isGuest } from '@/utils/auth'
@@ -36,6 +36,7 @@ const SORT_TABS: { key: SortKey; label: string }[] = [
]
const ShopPage: React.FC = () => {
const { addItem } = useCartContext()
const [categoryList, setCategoryList] = useState<any[]>(PRESET_CATEGORIES)
const [activeCategory, setActiveCategory] = useState(0)
@@ -146,14 +147,7 @@ const ShopPage: React.FC = () => {
const handleAddToCart = (e: any, product: ShopGoods) => {
e.stopPropagation()
if (!requireLogin({ action: 'addToCart' })) return
addToCart({
goodsId: product.goodsId!,
cartNum: product.step || 1,
}).then(() => {
Taro.showToast({ title: '已加入购物车', icon: 'success' })
}).catch(err => {
Taro.showToast({ title: err.message || '添加失败', icon: 'none' })
})
addItem(product, undefined, product.step || 1).catch(() => {})
}
/** 搜索输入(防抖 500ms */