微信小程序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) //记得关掉计时器
    },

  

 

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