微信小程序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) //記得關掉計時器
    },

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章