小程序网络请求默认为异步请求,在appjs的onLaunch运行后进行异步请求时,程序不会停止,Page页已执行onload, 我们希望onLaunch执行完后再执行onload。
//app.js
App({
onLaunch:function(){
let self=this;
wx.request({
url:'http://test.cn/login',//仅为示例,并非真实的接口地址
data: {},
success:function(res){
this.globalData.checkLogin =true;
//由于这里是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
if(self.checkLoginReadyCallback){
self.checkLoginReadyCallback(res);
}
}
})
},
globalData: {
checkLogin:false
}
})
//index.js
//获取应用实例
constapp = getApp()
Page({
data: {
test:false
},
onLoad:function(){
letthat =this;
//判断onLaunch是否执行完毕
if(app.globalData.checkLogin){
that.setData({
test:true
})
}else{
app.checkLoginReadyCallback =res=>{
that.setData({
test:true
})
};
}
}
})
网友评论