原生小程序 TS :清除缓存后关闭微信开发者工具,再导入项目,第一次启动的时候编译失败,要用户重新进入小程序才行,这是机制还是bug?冷启动:如果用户首次打开,或小程序销毁后被用户再次打开,此时小程序需要重新加载启动,即冷启动。
// app.ts
import { StorageService } from './utils/storage';
import SmartDoorMQTTClient from './utils/mqtt-client';
App<IAppOption>({
globalData: {
userInfo: undefined,
isLoggedIn: false,
__pageNavigating: false // 导航标记
},
onLaunch() {
// 初始化登录状态
const isLoggedIn = StorageService.isLoggedIn();
this.globalData.isLoggedIn = isLoggedIn;
// 获取用户信息
if (isLoggedIn) {
const userProfile = StorageService.getUserProfile();
if (userProfile) {
this.globalData.userInfo = userProfile;
}
} else {
// 未登录,直接跳转到登录页
console.log('用户未登录,跳转到登录页');
wx.redirectTo({
url: '/pages/login/login',
fail: function () {
// 如果在tabBar页面,则使用reLaunch
wx.reLaunch({
url: '/pages/login/login'
});
}
});
}
},
onShow() {
// 每次显示时检查登录状态
const isLoggedIn = StorageService.isLoggedIn();
if (this.globalData.isLoggedIn !== isLoggedIn) {
this.globalData.isLoggedIn = isLoggedIn;
}
},
// 添加 onHide 方法处理小程序进入后台的情况
onHide() {
// 检查是否登录
if (!this.globalData.isLoggedIn) {
return;
}
try {
// 获取 MQTT 客户端实例并发送离线消息
const mqttClient = SmartDoorMQTTClient.getInstance();
if (mqttClient && mqttClient.isConnected()) {
mqttClient.publishServerOffline();
}
} catch (error) {
console.error('[App] 发送离线消息时出错:', error);
}
}
});
现在开发者工具难用的很感觉屎山代码多得很😂