bugfix:未登录循环注册
This commit is contained in:
@@ -1,4 +1,10 @@
|
||||
import { request } from '../utils/request'
|
||||
import * as auth from '../utils/auth'
|
||||
import { STORAGE_KEYS } from '../utils/config'
|
||||
|
||||
// 未读红点轮询最小间隔,避免频繁切 tab 时重复打接口
|
||||
const SYNC_INTERVAL = 30 * 1000
|
||||
let lastSyncAt = 0
|
||||
|
||||
Component({
|
||||
data: {
|
||||
@@ -15,25 +21,40 @@ Component({
|
||||
|
||||
lifetimes: {
|
||||
attached() {
|
||||
this.refreshUnread()
|
||||
// 先用缓存渲染红点;未登录时不再发请求(否则会批量 401 并触发重定向)
|
||||
const cached = (wx.getStorageSync(STORAGE_KEYS.UNREAD) as number) || 0
|
||||
this.setData({ unread: cached })
|
||||
this.syncUnread()
|
||||
},
|
||||
},
|
||||
|
||||
methods: {
|
||||
refreshUnread() {
|
||||
const unread = (wx.getStorageSync('zt_closet_unread') as number) || 0
|
||||
// 直接更新红点(供页面在已知数量时调用,不再触发二次请求)
|
||||
setUnread(n: number) {
|
||||
const unread = Number(n) || 0
|
||||
wx.setStorageSync(STORAGE_KEYS.UNREAD, unread)
|
||||
this.setData({ unread })
|
||||
this.fetchUnread()
|
||||
},
|
||||
fetchUnread() {
|
||||
request<{ unread_count: number }>({ url: '/notification/unread', showError: false })
|
||||
.then((res) => {
|
||||
const unread = res.unread_count || 0
|
||||
wx.setStorageSync('zt_closet_unread', unread)
|
||||
this.setData({ unread })
|
||||
})
|
||||
|
||||
// 拉取未读数:仅登录态才请求,且做节流
|
||||
syncUnread(force?: boolean) {
|
||||
if (!auth.isLoggedIn()) {
|
||||
this.setUnread(0)
|
||||
return
|
||||
}
|
||||
const now = Date.now()
|
||||
if (!force && now - lastSyncAt < SYNC_INTERVAL) return
|
||||
lastSyncAt = now
|
||||
|
||||
request<{ unread_count: number }>({
|
||||
url: '/notification/unread',
|
||||
showError: false,
|
||||
silentAuth: true,
|
||||
})
|
||||
.then((res) => this.setUnread(res.unread_count || 0))
|
||||
.catch(() => {})
|
||||
},
|
||||
|
||||
switchTab(e: WechatMiniprogram.TouchEvent) {
|
||||
const { path, index } = e.currentTarget.dataset as { path: string; index: number }
|
||||
wx.switchTab({ url: path })
|
||||
|
||||
Reference in New Issue
Block a user