userInfoReadyCallback 在頁面中定義,在 app.js 中使用,使用場景是你需要獲取完用戶信息之后立即使用。如果你是在一進(jìn)落地頁就把用戶信息存本地,然后進(jìn)入個(gè)人中心頁面再從本地取出來,是不需要使用這個(gè)的。
附app.js代碼:
// 獲取用戶信息
wx.getSetting({
success: res => {
if (res.authSetting['scope.userInfo']) {
// 已經(jīng)授權(quán),可以直接調(diào)用 getUserInfo 獲取頭像昵稱,不會(huì)彈框
wx.getUserInfo({
success: res => {
// 可以將 res 發(fā)送給后臺(tái)解碼出 unionId
this.globalData.userInfo = res.userInfo
// 由于 getUserInfo 是網(wǎng)絡(luò)請(qǐng)求,可能會(huì)在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
}
})
}
}
})
if (this.userInfoReadyCallback) {
this.userInfoReadyCallback(res)
}
上面這句是判斷 userInfoReadyCallback 是否定義了,若沒定義,說明其在 Page.onLoad 定義 userInfoReadCallback 之前運(yùn)行的,說明 app.globalInfo.userInfo 已經(jīng)包含了用戶登錄的信息了。若定義了,說明 Page.onLoad 在該語句返回的 success 結(jié)果之前已經(jīng)運(yùn)行了。但是頁面獲取的 app.globalInfo.userInfo 的值是空的,所以還需要再重新對(duì)其進(jìn)行賦值(并不是重新執(zhí)行方法,只是重新復(fù)制)。
再附上index.js代碼:
//獲取應(yīng)用實(shí)例
const app = getApp()
Page({
onLoad: function () {
if(app.globalData.userInfo) {
// 由于 getUserInfo 是網(wǎng)絡(luò)請(qǐng)求,可能會(huì)在 Page.onLoad 之后才返回
// 所以此處加入 callback 以防止這種情況
app.userInfoReadyCallback = res => {
this.setData({
userInfo: res.userInfo
})
}
} else {
this.setData({
userInfo: app.globalData.userInfo
})
}
}
})
Page.onLoad 中首先會(huì)判斷 app.globalData.userInfo 是否存在,如果不存在,就在全局定義一個(gè)函數(shù) userInfoReadyCallback,這個(gè)函數(shù)的作用是接收全局登錄返回的用戶數(shù)據(jù),并存到頁面中。
總結(jié):這種模式是通過判斷一個(gè)全局變量是否存在來決定是否執(zhí)行回調(diào)的。如果這個(gè)全局變量不存在,也就是說 Page.onLoad 在 App.onLaunch 執(zhí)行完之前執(zhí)行了,那么我們就在 Page.onLoad 中掛載一個(gè)回調(diào)函數(shù),等 App.onLaunch 執(zhí)行完所有的異步后會(huì)判斷全局是否定義了這個(gè)回調(diào)函數(shù),如果定義了,就調(diào)用這個(gè)回調(diào)重新賦值。

