问题描述:
//app.js
App({
globalData:{
nickname:''
},
onLaunch: function () {
let that=this;
//假设已经授权成功
wx.getUserInfo({
success(res){
//获取用户信息并赋值给globalData
that.globalData.nickname=res.userInfo.nickName;
}
}) }
}) //index.js
const app = getApp()
Page({
data: {
myNickName:''
},
onLoad: function (option) {
console.log(app.globalData.nickname); //结果:""
this.setData({
myNickName:app.globalData.nickname
})
//由于wx.getUserInfo()是异步请求,不知道什么时候成功返回数据,导致获取失败
}
})
时序图描述:
解决方案
//app.js
App({
globalData:{
nickname:''
},
onLaunch: function () {
let that=this;
//假设已经授权成功
wx.getUserInfo({
success(res) {
let tmp=res; setTimeout(()=>{//更清楚的模拟异步环境,设置5秒后执行代码
//获取用户信息并赋值给globalData
that.globalData.nickname = res.userInfo.nickName;
if (that.userInfoReadyCallback) {
console.log('call back')
that.userInfoReadyCallback(res.userInfo.nickName)
}
},5000) }
}) }
}) //index.js
const app = getApp()
Page({
data: {
myNickName:''
},
onLoad: function (option) {
let that = this;
let mynickname = app.globalData.nickname;
//如果app.onLaunch中的wx.getUserInfo()返回够快
//在app.onLoad之前就已经初始化了app.globalData.nickname则直接更新本界面的this.data.nickname
if(mynickname.length){
this.setData({
nickname:mynickname
})
//定义回调函数,一旦app.onLaunch的wx.getUserInfo获取到用户信息的时候,立即运行该回调函数
}else{
app.userInfoReadyCallback=res=>{
this.setData({
nickname:res
})
}
}
}
})
解决方案时序图:
总结
1.巧用回调函数
参考:https://blog.csdn.net/zjw_python/article/details/80641963