这是一个很关键的问题,在实际开发中也经常困扰开发者:
🎯 问题本质:
小程序明明 触发了冷启动(走了
App.onLaunch
),但是页面的onLoad()
却 没有重新执行。
✅ 这是官方允许的一种「优化行为」,其发生的典型场景是:
✅ 场景一:冷启动恢复到上次停留的页面
微信小程序有一个「页面保活机制」:
- 用户冷启动打开小程序,但 上一次退出前的页面仍然保留在栈中;
- 系统将直接恢复到那个页面;
- 页面不会销毁,因此不会重新触发
onLoad()
,而只会走onShow()
。
👉 这种情况下,App 是冷启动的,但页面不是全新加载的页面。
🔍 你可以通过 App.onLaunch()
打印的 path / scene
判断:
1 2 3 4 5 6 7 |
App({ onLaunch(options) { console.log('冷启动 scene:', options.scene) console.log('path:', options.path) } }) |
如果 options.path
是一个非首页页面路径,而且你发现这个页面的 onLoad()
没有执行,说明微信帮你恢复了上次页面栈。
✅ 如何判断当前页面是否是首次进入?
你可以在页面中这样判断是否「onLoad 没执行」:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
Page({ onLoad() { console.log('✅ 页面 onLoad 被执行') this.setData({ firstLoad: true }) }, onShow() { console.log('页面 onShow 被执行') if (!this.data.firstLoad) { console.log('❗ 页面未走 onLoad,但走了 onShow,说明是页面恢复') this.initData() // 做一次补救加载 } } }) |
✅ 如何强制让小程序每次都重新加载首页?
可以设置小程序的 "restartStrategy"
:
小程序
app.json
中设置:
1 2 3 4 5 6 |
{ "pages": ["pages/index/index", "pages/xxx/xxx"], "entryPagePath": "pages/index/index", "restartStrategy": "homePage" } |
restartStrategy | 说明 |
---|---|
homePage (默认) | 冷启动后固定跳转到首页 |
lastPage | 冷启动后恢复到上一次页面栈 |
你设置为 homePage
后,每次冷启动都重新进首页,会触发 onLoad()
。
✅ 小结一下
场景 | App.onLaunch | 页面onLoad | 页面onShow |
---|---|---|---|
冷启动首次打开小程序 | ✅ 是 | ✅ 是 | ✅ 是 |
冷启动恢复上次页面(页面保活) | ✅ 是 | ❌ 否 | ✅ 是 |
后台切前台 | ❌ 否 | ❌ 否 | ✅ 是 |
页面 redirectTo / switchTab | ❌ 否 | ✅ 是 | ✅ 是 |
如果你希望强制刷新页面数据而不依赖 onLoad()
,推荐统一在 onShow()
中判断状态拉取。