微信小程序app.js 內容加載速度比 index.js 慢導致無法獲取到全局用戶對象


一、場景

我在app.js 的onload 進行wx.login 取到code,用code 去調用api服務器換取openid並且獲取用戶信息回來緩存到  globalData.userinfo 緩存起來

在首頁的index.js 的onload  獲取 getApp().globalData.userinfo 進行邏輯處理,發現是空的,但過一會就有了。

二、原因

app.js的onload的wx.request是異步,所以在index.js加載的時候它還沒獲取到數據,過一會就有了

三、解決方案

1、在app.js wx.request的success進行處理index.js的邏輯(或回調函數進行處理邏輯)

2、用promise,在app.js onload 返回promise,index.js進行then處理。

3、使用定時器,在index.js里一直執行,直到userinfo不為null

 

這邊采用第三種

在index.js 的寫上

onHide:function(){
//記得在這邊關閉頁面或者跳轉頁面寫入關閉計時器
clearInterval(this.data.setInter)

},
onUnload:function(){
//記得在這邊頁面卸載
clearInterval(this.data.setInter)

},


onload:function(){
this.getUserInfo
},
getUserInfo: function() { var t = this; if(t.data.baseinfo) { console.log('早有了'); return ; } t.data.setInter = setInterval( function () { t.queryUserInfo() }, 1000); },
queryUserInfo: function () {
        var t = this;
        if (app.globalData.userInfo == null) {
            console.log('無')
          return
        }
        console.log('有')
        var userinfo=app.globalData.userInfo;      
          t.setData({
              baseinfo: basemin
          })
           clearInterval(t.data.setInter) //記得關掉計時器
    },

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM