获取用户信息主要在app.js 和 index.js中
app.js
App({onLaunch: function () {// 展示本地存储能力var logs = wx.getStorageSync('logs') || []logs.unshift(Date.now())wx.setStorageSync('logs', logs)// 登录wx.login({success: res => {}})// 获取用户信息wx.getSetting({success: res => {if (res.authSetting['scope.userInfo']) {// 已经授权,可以直接调用 getUserInfo 获取头像昵称,不会弹框wx.getUserInfo({success: res => {// 可以将 res 发送给后台解码出 unionIdthis.globalData.userInfo = res.userInfo// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回// 所以此处加入 callback 以防止这种情况if (this.userInfoReadyCallback) {this.userInfoReadyCallback(res)}}})}}})},globalData: {userInfo: null,}})
index.js
//获取应用实例const app = getApp()Page({data: {motto: '欢迎使用迷你计算器',userInfo: {},hasUserInfo: false,canIUse: wx.canIUse('button.open-type.getUserInfo')},//事件处理函数bindViewTap: function() {wx.navigateTo({url: '../logs/logs'})},onLoad: function () {if (app.globalData.userInfo) {this.setData({userInfo: app.globalData.userInfo,hasUserInfo: true})} else if (this.data.canIUse){// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回// 所以此处加入 callback 以防止这种情况app.userInfoReadyCallback = res => {this.setData({userInfo: res.userInfo,hasUserInfo: true})}} else {// 在没有 open-type=getUserInfo 版本的兼容处理wx.getUserInfo({success: res => {app.globalData.userInfo = res.userInfothis.setData({userInfo: res.userInfo,hasUserInfo: true})}})}},getUserInfo: function(e) {console.log(e)app.globalData.userInfo = e.detail.userInfothis.setData({userInfo: e.detail.userInfo,hasUserInfo: true})}})
首先执行的是app.js的wx.getUserInfo,这个是获取用户信息的网络请求,由于其返回结果不知道在index页面加载完成之前还是之后完成,因此分为两种情况:
- 在index页面加载完成之前返回:此时优先执行app.js中success函数的代码,
app.globalData.userInfo就保存了用户信息。运行到这里时,由于userInfoReadyCallback函数是在index.onload中定义的,因此此时该函数并没有被定义,所以不执行该函数。之后执行index.js中onload中的代码,执行第一个if分支,赋值给页面的userInfo和hasUserInfo
if (this.userInfoReadyCallback) {this.userInfoReadyCallback(res)}
- 在index页面加载完成之后返回:此时优先执行index.js中onload中的代码,由于用户信息还没有返回,所以
app.globalData.userInfo为null,执行第二个if分支,定义userInfoReadyCallback函数。随后数据被返回,执行success的代码,app.globalData.userInfo在此时才保存了用户的信息,并执行userInfoReadyCallback函数,赋值给页面的userInfo和hasUserInfo
userInfoReadyCallback函数的作用,就是保证页面的userInfo和hasUserInfo被正确赋值,无论用户信息在页面加载完成之前还是之后返回。
