參考:小程序如何在其他頁面監聽globalData中值的變化?https://www.jianshu.com/p/8d1c4626f9a3
原因就是:app.js沒執行完時,其他頁已經onload了,所以取不到globalData
解決辦法就是用回調函數
app.js
//app.js App({ globalData: { }, onLaunch: function() { }, //獲取openid,由於網絡延時,通常在其他頁onload之后才會success,所以從其他頁傳回調函數cb進來。 getopenid: function(cb) { if (this.globalData.openid) { typeof cb == "function" && cb(this.globalData.openid) } else {
var that = this wx.cloud.callFunction({ name: 'login', data: {}, success: res => { //閉包函數內,可以用this,而不需要用that=this that.globalData.openid = res.result.openid typeof cb == "function" && cb(that.globalData.openid) }, fail: err => { wx.showToast({ icon: 'none', title: '獲取 openid 失敗,請檢查 login 雲函數', }) console.log('[雲函數] [login] 獲取 openid 失敗,請檢查是否有部署雲函數,錯誤信息:', err) }, }) } }, })
在其他頁面上,onload中 const app = getApp() 用app.getopenid調用app.js中的函數,並傳入參數that.cb
onLoad: function(options) { //設置回調,防止小程序globalData拿到數據為null let that = this; app.getopenid(that.cb) }, cb: function(res) { let that = this console.log("write cb res", res) that.setData({ openid: res }) },
這樣當App.js中的getopenid有返回值時,就會更新到其他頁面
還可以將that.cb寫成閉包函數,就不用 let that =this了
onLoad: function(options) { //設置回調,防止小程序globalData拿到數據為null app.getopenid(res => { console.log("write cb res", res) this.setData({ openid: res }) }) },