微信小程序-解决index页面onload比app.js onlaunch请求快

首先要说明在小程序中,app.js和index.js是异步执行的,也就说明可能当你app.js中onlaunch的登录、通过code获取open_id之类的网络请求在执行的时候,index.js中的onload已经执行完了,如果你在index的onload中有需要用到openid的话,那就会无法执行调用了。

这个时候就需要通过用 请求的callback方法啦,如果你细心去看,其实在app.js的获取用户信息中,已经帮你写好了回调。

// 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
// 所以此处加入 callback 以防止这种情况
 if (this.userInfoReadyCallback) {
   this.userInfoReadyCallback(res)
  }

上面这句是判断userInfoReadyCallback是否已经定义,如果还没有定义,说明这里的网络请求在index.onload定义userInfoReadyCallback之前运行,这个时候说明app.globalData.user_id已经存在。

如果userInfoReadyCallback已经定义了,说明index.onload已经执行了,此时app.globalData.user_id为null,所以需要重新赋值,及在index.onload的回调中进行赋值

接下来就是在index.js中的onload里面判断是否已经有openid,如果已经存在openid,那么就不会影响你接下来的操作,如果没有就执行回调方法,在回调方法中就可以获取到你需要的值

if(!app.globalData.user_id){
 app.userInfoReadyCallback = res => {
  //业务代码
  }
}

详细代码↓
app.js

// 登录
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        console.log(res)
        wx.request({
          url: that.globalData.url + 'code_to_openid',
          method:'post',
          header: { 'Content-Type': 'application/x-www-form-urlencoded' },
          data:{
            code:res.code
          },
          success(res){
            console.log(res)
            that.globalData.user_id = res.data.data.id
            that.globalData.unionid = res.data.data.unionid
            that.globalData.user_info = res.data.data
            //callback
            if (that.userInfoReadyCallback) {
              that.userInfoReadyCallback(res)
            }
          }
        })
      }
    })

index.js

  onLoad: function() {
    let that = this
    //查看是否有userid
    if(!app.globalData.user_id){
      app.userInfoReadyCallback = res => {
        //判断是否阅读过引导页
        wx.request({
          url: app.globalData.url + 'checkfirst',
          method: 'POST',
          header: { "Content-Type": "application/x-www-form-urlencoded" },
          data: {
            user_id: app.globalData.user_id
          }, success(res) {
            console.log(res)
            if (res.data.resultCode == 0 || res.data.resultCode == ''){
              wx.hideTabBar()
              that.setData({
                guide_show:true
              })
            }
          }
        })
      }
    }
  }

你可能感兴趣的:(微信小程序-解决index页面onload比app.js onlaunch请求快)