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) //记得关掉计时器
        },

      

  • 相关阅读:
    Leetcode 148. Sort List
    stat/lstat函数使用
    C/C++内存分配和管理
    initializer_list 列表初始化
    extern "C" 含义
    C语言宏定义##连接符和#符的使用
    rabbitMQ日常管理(转)
    java/rabbitmp发布订阅示例(转)
    oracle分页查询
    oracle imp使用
  • 原文地址:https://www.cnblogs.com/wdw31210/p/13070990.html
Copyright © 2011-2022 走看看