zoukankan      html  css  js  c++  java
  • 微信小程序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) //记得关掉计时器
        },

      

  • 相关阅读:
    REDELK的安装和使用
    Palo Alto GlobalProtect上的PreAuth RCE
    渗透 Facebook 的思路与发现
    抓取腾讯视频MP4文件
    JS中整数的取整、取余、向上取整
    centos7安装docker
    业界难题-“跨库分页”的四种方案(转)
    centos7设置时间
    简单实现Shiro单点登录(自定义Token令牌)
    nginx 反向代理时丢失端口的解决方案(转)
  • 原文地址:https://www.cnblogs.com/wdw31210/p/13070990.html
Copyright © 2011-2022 走看看