赞
踩
小程序onLaunch异步,首页onLoad却先执行的解决办法
首先在app.js中的onLaunch中写入一个你要先执行的调用方法。如图:
我这里要在最开始onload之前获取到网络状态:
getNetworkInfo()
//onLaunch异步,首页onLoad先执行bug的处理
getNetworkInfo:function(cb){
var that = this
if(that.globalData.isBtnStatus.NetworkStatus != '0'){
typeof cb == "function" && cb(that.globalData.isBtnStatus.NetworkStatus)
}else{
wx.getNetworkType({
success: function(res) {
//console.log('onLaunch网络:'+res.networkType);
// 返回网络类型, 有效值:wifi/2g/3g/4g/unknown(Android下不常见的网络类型)/none(无网络)
var networkType = res.networkType
if (networkType != 'none') {
that.globalData.isBtnStatus.NetworkStatus = 1;
typeof cb == "function" && cb(1);
}
}
})
wx.onNetworkStatusChange(function(res) {
if (that.globalData.isBtnStatus.NetworkStatus != res.isConnected
&& true == res.isConnected) {
// WxNotificationCenter.postNotificationName("NetworkPageRefresh", true);
}
that.globalData.isBtnStatus.NetworkStatus = res.isConnected;
typeof cb == "function" && cb( that.globalData.isBtnStatus.NetworkStatus);
})
}
},
然后再在项目pages里面的首页index.js中的onload里面取值:
app.getNetworkInfo(function(retStatus){
//console.log('onLoad网络NetworkStatus1:'+retStatus);
//console.log('onLoad网络NetworkStatus2:'+app.globalData.isBtnStatus.NetworkStatus);
if (app.globalData.isBtnStatus.NetworkStatus == 1) {
that.networkSucc(that);
}else{
that.networkFail(that);
}
})
逻辑是:当进入onload,如果有网络就处理加载项目数据,如果没有网络就给出没网络的友好提示图片页面。
The end
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。