小程序onLaunch異步,首頁onLoad卻先執(zhí)行的解決辦法
創(chuàng)新互聯(lián)專業(yè)為企業(yè)提供成安網(wǎng)站建設、成安做網(wǎng)站、成安網(wǎng)站設計、成安網(wǎng)站制作等企業(yè)網(wǎng)站建設、網(wǎng)頁設計與制作、成安企業(yè)網(wǎng)站模板建站服務,10多年成安做網(wǎng)站經驗,不只是建網(wǎng)站,更提供有價值的思路和整體網(wǎng)絡服務。
首先在app.js中的onLaunch中寫入一個你要先執(zhí)行的調用方法。如圖:
我這里要在最開始onload之前獲取到網(wǎng)絡狀態(tài):
getNetworkInfo()
//onLaunch異步,首頁onLoad先執(zhí)行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網(wǎng)絡:'+res.networkType);
// 返回網(wǎng)絡類型, 有效值:wifi/2g/3g/4g/unknown(Android下不常見的網(wǎng)絡類型)/none(無網(wǎng)絡)
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網(wǎng)絡NetworkStatus1:'+retStatus);
//console.log('onLoad網(wǎng)絡NetworkStatus2:'+app.globalData.isBtnStatus.NetworkStatus);
if (app.globalData.isBtnStatus.NetworkStatus == 1) {
that.networkSucc(that);
}else{
that.networkFail(that);
}
})
邏輯是:當進入onload,如果有網(wǎng)絡就處理加載項目數(shù)據(jù),如果沒有網(wǎng)絡就給出沒網(wǎng)絡的友好提示圖片頁面。
思路來源:
https://blog.csdn.net/qq_29246395/article/details/77567365
The end