Browse Source

修复主页面货源收藏状态显示不一致问题

pull/1/head
Default User 2 months ago
parent
commit
abd03df40d
  1. 136
      pages/index/index.js
  2. 15
      server-example/server-mysql.js
  3. 11
      utils/api.js

136
pages/index/index.js

@ -245,6 +245,37 @@ Page({
} }
}); });
}, 500); }, 500);
// 添加收藏状态变化事件监听
const app = getApp();
this.favoriteChangedHandler = (data) => {
console.log('收到收藏状态变化通知:', data);
// 更新商品列表中对应商品的收藏状态
const updatedGoods = this.data.goods.map(item => {
if (String(item.id || item.productId) === data.productId) {
return {
...item,
isFavorite: data.isFavorite
};
}
return item;
});
this.setData({
goods: updatedGoods
}, () => {
// 重新应用筛选条件,确保显示的商品收藏状态也更新
const filteredGoods = this.applyFilters(this.data.goods);
const { leftColumnGoods, rightColumnGoods } = this.distributeToColumns(filteredGoods);
this.setData({
filteredGoods: filteredGoods,
leftColumnGoods: leftColumnGoods,
rightColumnGoods: rightColumnGoods
});
});
};
app.eventBus.on('favoriteChanged', this.favoriteChangedHandler);
}, },
onShow: function () { onShow: function () {
@ -271,6 +302,15 @@ Page({
}); });
}, },
onUnload: function () {
// 页面卸载时移除收藏状态变化事件监听
const app = getApp();
if (this.favoriteChangedHandler) {
app.eventBus.off('favoriteChanged', this.favoriteChangedHandler);
console.log('移除收藏状态变化事件监听');
}
},
onPullDownRefresh: function() { onPullDownRefresh: function() {
this.onRefresh() this.onRefresh()
}, },
@ -404,6 +444,9 @@ Page({
newGoods = newGoods.filter(item => (item.status || '').toLowerCase() !== 'hidden') newGoods = newGoods.filter(item => (item.status || '').toLowerCase() !== 'hidden')
// 更新商品的收藏状态
this.updateGoodsFavoriteStatus(newGoods, isLoadMore)
// 只在第一页或刷新时在商品列表最前面插入广告 // 只在第一页或刷新时在商品列表最前面插入广告
if ((!isLoadMore || this.data.page === 1) && newGoods.length > 0) { if ((!isLoadMore || this.data.page === 1) && newGoods.length > 0) {
// 确保广告位在最前面 // 确保广告位在最前面
@ -580,13 +623,7 @@ Page({
if (this.data.selectedCategory !== '全部') { if (this.data.selectedCategory !== '全部') {
const category = this.data.selectedCategory const category = this.data.selectedCategory
let keyword = category filtered = filtered.filter(item => item.isAd || (item.category === category))
if (category === '粉壳') keyword = '粉'
else if (category === '绿壳') keyword = '绿'
else if (category === '红壳') keyword = '红'
else if (category === '白壳') keyword = '白'
filtered = filtered.filter(item => item.isAd || (item.name || '').includes(keyword))
} }
if (this.data.searchKeyword) { if (this.data.searchKeyword) {
@ -946,6 +983,91 @@ Page({
app.globalData.showTabBar = true; app.globalData.showTabBar = true;
}, },
// 更新商品的收藏状态
updateGoodsFavoriteStatus: function(goods, isLoadMore) {
// 获取用户手机号
let userPhone = '';
try {
const users = wx.getStorageSync('users') || {};
const userId = wx.getStorageSync('userId');
// 尝试从users中获取手机号
if (userId && users[userId] && users[userId].phoneNumber) {
userPhone = users[userId].phoneNumber;
} else {
// 尝试从全局用户信息获取
const userInfo = wx.getStorageSync('userInfo');
if (userInfo && userInfo.phoneNumber) {
userPhone = userInfo.phoneNumber;
} else {
// 尝试从直接存储的phoneNumber获取
userPhone = wx.getStorageSync('phoneNumber');
}
}
} catch (e) {
console.error('获取用户手机号失败:', e);
}
if (!userPhone) {
// 用户未登录,无法获取收藏状态
return;
}
// 调用API获取用户收藏列表
API.getFavorites(userPhone)
.then(res => {
if (res && res.code === 200) {
// 检查API返回的数据结构,确保我们获取到正确的收藏列表
let favoritesList = [];
if (Array.isArray(res.data)) {
favoritesList = res.data;
} else if (res.data && Array.isArray(res.data.favorites)) {
favoritesList = res.data.favorites;
} else if (res.data && Array.isArray(res.data.data)) {
favoritesList = res.data.data;
}
// 从收藏列表中提取商品ID
const favoriteProductIds = favoritesList.map(item => {
// 尝试从不同的字段名获取商品ID
return String(item.productId || item.id || item.product_id || '');
}).filter(id => id !== ''); // 过滤掉空字符串
// 更新商品的isFavorite状态
const updatedGoods = goods.map(item => ({
...item,
isFavorite: favoriteProductIds.includes(String(item.id || item.productId))
}));
// 更新商品列表
let updatedGoodsList = this.data.goods;
if (!isLoadMore || this.data.page === 1) {
// 第一页或刷新时,直接替换全部商品
updatedGoodsList = updatedGoods;
} else {
// 加载更多时,追加到现有列表
updatedGoodsList = [...this.data.goods, ...updatedGoods];
}
this.setData({
goods: updatedGoodsList
}, () => {
// 重新应用筛选条件,确保显示的商品收藏状态也更新
const filteredGoods = this.applyFilters(this.data.goods);
const { leftColumnGoods, rightColumnGoods } = this.distributeToColumns(filteredGoods);
this.setData({
filteredGoods: filteredGoods,
leftColumnGoods: leftColumnGoods,
rightColumnGoods: rightColumnGoods
});
});
}
})
.catch(err => {
console.error('获取收藏状态失败:', err);
});
},
// 回到顶部 // 回到顶部
scrollToTop: function() { scrollToTop: function() {
this.setData({ this.setData({

15
server-example/server-mysql.js

@ -834,6 +834,11 @@ Product.init({
type: DataTypes.STRING(50), type: DataTypes.STRING(50),
allowNull: true, allowNull: true,
comment: '供应状态' comment: '供应状态'
},
category: {
type: DataTypes.STRING(50),
allowNull: true,
comment: '商品种类'
} }
}, { }, {
sequelize, sequelize,
@ -1777,7 +1782,7 @@ app.post('/api/user/update', async (req, res) => {
// 获取商品列表 - 优化版本确保状态筛选正确应用 // 获取商品列表 - 优化版本确保状态筛选正确应用
app.post('/api/product/list', async (req, res) => { app.post('/api/product/list', async (req, res) => {
try { try {
const { openid, status, keyword, page = 1, pageSize = 20, testMode = false, viewMode = 'shopping' } = req.body; const { openid, status, keyword, category, page = 1, pageSize = 20, testMode = false, viewMode = 'shopping' } = req.body;
// 查找用户 - 如果提供了openid,则查找用户信息,否则允许匿名访问 // 查找用户 - 如果提供了openid,则查找用户信息,否则允许匿名访问
let user = null; let user = null;
@ -1870,6 +1875,11 @@ app.post('/api/product/list', async (req, res) => {
where.productName = { [Sequelize.Op.like]: `%${keyword}%` }; where.productName = { [Sequelize.Op.like]: `%${keyword}%` };
} }
// 分类筛选
if (category) {
where.category = { [Sequelize.Op.eq]: category };
}
// 计算偏移量 // 计算偏移量
const offset = (page - 1) * pageSize; const offset = (page - 1) * pageSize;
@ -1887,7 +1897,8 @@ app.post('/api/product/list', async (req, res) => {
include: [ include: [
'region', // 【新增】确保返回地区字段 'region', // 【新增】确保返回地区字段
'sourceType', // 【新增】确保返回货源类型字段 'sourceType', // 【新增】确保返回货源类型字段
'supplyStatus' // 【新增】确保返回供应状态字段 'supplyStatus', // 【新增】确保返回供应状态字段
'category' // 【新增】确保返回商品种类字段
] ]
}, },
order: [['created_at', 'DESC']], order: [['created_at', 'DESC']],

11
utils/api.js

@ -887,6 +887,7 @@ module.exports = {
yolk: product.yolk || '', yolk: product.yolk || '',
specification: product.specification || '', specification: product.specification || '',
region: product.region || '', // 【新增】添加地区字段 region: product.region || '', // 【新增】添加地区字段
category: product.category || '', // 【新增】添加种类字段
// imageUrls字段会被忽略,因为图片会通过wx.uploadFile上传 // imageUrls字段会被忽略,因为图片会通过wx.uploadFile上传
} }
@ -1410,6 +1411,16 @@ module.exports = {
requestData.viewMode = options.viewMode; requestData.viewMode = options.viewMode;
} }
// 如果options中包含category,则添加到请求数据中
if (options.category) {
requestData.category = options.category;
}
// 如果options中包含keyword,则添加到请求数据中
if (options.keyword) {
requestData.keyword = options.keyword;
}
console.log('API.getProductList - 分页参数:', { page: page, pageSize: pageSize }); console.log('API.getProductList - 分页参数:', { page: page, pageSize: pageSize });
console.log('API.getProductList - 请求数据:', requestData); console.log('API.getProductList - 请求数据:', requestData);

Loading…
Cancel
Save