Browse Source

feat: 优化筛选缓存逻辑

- 点击筛选时优先使用本地缓存,避免重复查询数据库
- 下拉加载更多时强制请求服务器,确保数据完整性
- 修复切换分类时数据丢失问题
- 缓存有效期设置为5分钟
pull/1/head
徐飞洋 2 months ago
parent
commit
69dbd4295b
  1. 121
      pages/index/index.js

121
pages/index/index.js

@ -49,6 +49,12 @@ Page({
page: 1, page: 1,
pageSize: 8, pageSize: 8,
// 商品数据缓存
goodsCache: [],
categoryQueryCache: {},
lastDataTimestamp: 0,
cacheValidDuration: 5 * 60 * 1000, // 缓存有效期5分钟
// 防抖定时器 // 防抖定时器
searchDebounceTimer: null, searchDebounceTimer: null,
scrollDebounceTimer: null, scrollDebounceTimer: null,
@ -676,12 +682,29 @@ Page({
}); });
}, },
// 加载商品数据 - 淘宝风格优化 // 加载商品数据 - 优化版带缓存
loadGoods: function(isLoadMore = false) { loadGoods: function(isLoadMore = false, forceRefresh = false) {
if (isLoadMore && !this.data.hasMoreData) { if (isLoadMore && !this.data.hasMoreData) {
return return
} }
const currentCategory = this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory;
const currentKeyword = this.data.searchKeyword;
const cacheKey = `${currentCategory}_${currentKeyword}`;
const now = new Date().getTime();
// 只有非加载更多模式才使用缓存
if (!isLoadMore && !forceRefresh &&
this.data.categoryQueryCache[cacheKey] &&
(now - this.data.lastDataTimestamp) < this.data.cacheValidDuration) {
console.log('使用缓存数据,cacheKey:', cacheKey);
const cachedGoods = this.data.categoryQueryCache[cacheKey];
// 更新timestamp以确保缓存有效
this.setData({ lastDataTimestamp: now });
this.processCachedGoods(cachedGoods, isLoadMore);
return;
}
if (isLoadMore) { if (isLoadMore) {
this.setData({ loadingMore: true }) this.setData({ loadingMore: true })
} else { } else {
@ -689,15 +712,15 @@ Page({
} }
const timestamp = new Date().getTime(); const timestamp = new Date().getTime();
const currentPage = isLoadMore ? this.data.page : 1 const page = isLoadMore ? this.data.page : 1
API.getProductList('published', { API.getProductList('published', {
timestamp: timestamp, timestamp: timestamp,
viewMode: 'shopping', viewMode: 'shopping',
page: currentPage, page: page,
pageSize: this.data.pageSize, pageSize: this.data.pageSize,
keyword: this.data.searchKeyword, keyword: currentKeyword,
category: this.data.selectedCategory === '全部' ? '' : this.data.selectedCategory category: currentCategory
}) })
.then(res => { .then(res => {
wx.hideLoading(); wx.hideLoading();
@ -713,9 +736,19 @@ Page({
if (res.success && res.products) { if (res.success && res.products) {
const totalGoods = res.total || 0; const totalGoods = res.total || 0;
const totalPages = res.totalPages || Math.ceil(totalGoods / this.data.pageSize); const totalPages = res.totalPages || Math.ceil(totalGoods / this.data.pageSize);
const hasMoreData = currentPage < totalPages && res.products.length > 0; const hasMoreData = page < totalPages && res.products.length > 0;
// 更新缓存
const updatedCache = { ...this.data.categoryQueryCache };
updatedCache[cacheKey] = res.products;
this.setData({
hasMoreData,
categoryQueryCache: updatedCache,
lastDataTimestamp: now,
goodsCache: res.products
})
this.setData({ hasMoreData })
this.processGoodsData(res.products, isLoadMore) this.processGoodsData(res.products, isLoadMore)
} else { } else {
this.setData({ loadingMore: false, isLoading: false }) this.setData({ loadingMore: false, isLoading: false })
@ -727,6 +760,59 @@ Page({
}) })
}, },
// 处理缓存的商品数据
processCachedGoods: function(cachedGoods, isLoadMore) {
console.log('processCachedGoods 被调用, isLoadMore:', isLoadMore);
// 处理商品数据格式
const processedGoods = cachedGoods.map(product => {
const imageUrls = product.imageUrls || product.images || [];
const formattedImageUrls = Array.isArray(imageUrls) ? imageUrls : [imageUrls];
return {
...product,
category: product.category || '',
fullRegion: product.region || '',
region: product.region ? this.extractProvince(product.region) : '',
grossWeight: product.grossWeight || product.weight || '',
displayGrossWeight: product.grossWeight || product.weight || '',
status: product.status || 'published',
createdAt: product.created_at || product.createTime || null,
reservedCount: product.reservedCount || product.selected || 0,
reservedCountDisplay: product.reservedCount || product.selected || 0,
sales: product.sales || product.reservedCount || Math.floor(Math.random() * 1000) + 100,
product_contact: product.product_contact || '',
contact_phone: product.contact_phone || '',
supplyStatus: product.supplyStatus || '',
sourceType: product.sourceType || '',
negotiateStatus: '可议价',
isReserved: false,
isFavorite: false,
currentImageIndex: 0,
imageUrls: formattedImageUrls
}
});
// 更新收藏状态
this.updateGoodsFavoriteStatus(processedGoods, false);
// 应用筛选条件
let filteredGoods = this.applyFilters(processedGoods, false);
// 分配到两列
const { leftColumnGoods, rightColumnGoods } = this.distributeToColumns(filteredGoods);
this.setData({
goods: processedGoods,
filteredGoods: filteredGoods,
leftColumnGoods: leftColumnGoods,
rightColumnGoods: rightColumnGoods,
loadingMore: false,
isLoading: false,
hasMoreData: false // 缓存数据不分页
});
},
// 刷新商品列表 // 刷新商品列表
refreshGoodsList: function() { refreshGoodsList: function() {
this.setData({ this.setData({
@ -1004,8 +1090,23 @@ Page({
isLoading: true isLoading: true
}) })
// 重新从服务器加载数据 const currentCategory = category === '全部' ? '' : category;
this.loadGoods(false) const currentKeyword = this.data.searchKeyword;
const cacheKey = `${currentCategory}_${currentKeyword}`;
const now = new Date().getTime();
// 检查缓存(首次加载时使用缓存,加载更多时不用)
if (this.data.categoryQueryCache[cacheKey] &&
(now - this.data.lastDataTimestamp) < this.data.cacheValidDuration) {
console.log('selectCategory使用缓存数据,cacheKey:', cacheKey);
const cachedGoods = this.data.categoryQueryCache[cacheKey];
// 更新timestamp以确保缓存有效
this.setData({ lastDataTimestamp: now });
this.processCachedGoods(cachedGoods, false);
} else {
// 重新从服务器加载数据
this.loadGoods(false)
}
}, },
// 查看商品详情 // 查看商品详情

Loading…
Cancel
Save