页面优化

This commit is contained in:
Dev
2026-10-19 15:46:10 +08:00
parent 44405743bb
commit 6beeeb2383
14 changed files with 229 additions and 120 deletions
+33 -19
View File
@@ -9,16 +9,16 @@ Component({
lifetimes: {
attached() {
//先用 globalData 缓存渲染,避免切换 tab 时红点闪没,再拉取最新
// 先用全局缓存渲染,避免切换 tab 时红点闪没。网络请求交给 show,并与其他实例共用节流
const app = getApp();
if (app && Number(app.globalData?.unread) > 0) {
this.setData({ unread: Number(app.globalData.unread) });
const unread = app && app.globalData ? Number(app.globalData.unread) || 0 : 0;
if (unread > 0) {
this.setData({ unread });
}
this.refreshUnread();
},
},
//所在 tab 页面显示时刷新(切换 tab、从其他页面返回均会触发)
// 当前 tab 显示时刷新。30s 内各实例只发一次请求
pageLifetimes: {
show() {
this.refreshUnread();
@@ -48,35 +48,46 @@ Component({
/**
* 从服务端拉取未读消息数
* 未登录/请求失败时保持 0(不显示红点),不影响 tabbar 正常使用
* 5s 内重复触发只发一次请求(app轮询/页面onShow/tabbar show 多处触发)
* 未登录时不显示红点。节流记在 globalData,切换 Tab 新建的 tabBar 实例也会共用
* 30s 内只发一次;消息页改未读数走 setUnread,不走这里
*/
refreshUnread(force = false) {
if (!wx.getStorageSync('token')) {
const app = getApp();
const token = (wx.$util && wx.$util.getToken && wx.$util.getToken()) || '';
if (!token) {
this.setData({ unread: 0 });
const app = getApp();
if (app) app.globalData.unread = 0;
if (app && app.globalData) {
app.globalData.unread = 0;
}
return;
}
const now = Date.now();
if (!force && now - (this._lastFetchAt || 0) < 5000) {
const last = app && app.globalData ? Number(app.globalData.unreadFetchedAt) || 0 : 0;
if (!force && now - last < 30000) {
if (app && app.globalData) {
this.setData({ unread: Number(app.globalData.unread) || 0 });
}
return;
}
//上一次请求尚未结束时不再发起,避免请求堆积占满并发导致页面假死
if (this._fetching) {
if (app && app.globalData && app.globalData.unreadFetching) {
return;
}
this._lastFetchAt = now;
this._fetching = true;
if (app && app.globalData) {
app.globalData.unreadFetching = true;
app.globalData.unreadFetchedAt = now;
}
const done = () => {
this._fetching = false;
if (app && app.globalData) {
app.globalData.unreadFetching = false;
}
};
fetchMessageUnreadCount().then((res) => {
if (res.code == 1) {
const unread = Number(res.data?.unread_count) || 0;
this.setData({ unread });
const app = getApp();
if (app) app.globalData.unread = unread;
if (app && app.globalData) {
app.globalData.unread = unread;
}
}
}).catch(() => {}).then(done, done);
},
@@ -88,7 +99,10 @@ Component({
const unread = Number(count) || 0;
this.setData({ unread });
const app = getApp();
if (app) app.globalData.unread = unread;
if (app && app.globalData) {
app.globalData.unread = unread;
app.globalData.unreadFetchedAt = Date.now();
}
},
},
});