收藏
回答

this.data与this.data.hasUserInfo中某字段的值不一致,请问是什么问题?

//index.js
//获取应用实例
const app = getApp()
const loginUrl = 'http://127.0.0.1:8090/api/mini/login';
Page({
  data: {
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  onLoad: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      })
      // console.log('if execute')
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        })
      }
      // console.log('else if execute,data:',this.data)
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
          // console.log('else execute')
        }
      })
    }
  },
  onReady: function(){
    console.log('ready:',this.data.hasUserInfo,this.data)
    if (this.data.canIUse && (this.data["hasUserInfo"])) {
      wx.switchTab({
        url: '/pages/home/home',
      })
    }
  },
  getUserInfo: function(e) {
    app.globalData.userInfo = e.detail.userInfo
    this.setData({
      userInfo: e.detail.userInfo,
      hasUserInfo: true
    })
    this.checkSession();
  },
  //自定义用户授权登录
  checkSession: function(){
    wx.checkSession({
      success: function () {
        console.log('用户已授权')
        wx.switchTab({
          url: '/pages/home/home',
        })
      },
      fail: function () {
        console.log('未授权,开始授权...')
        wx.login({
          success: function (res) {
            //发送请求
            wx.request({
              url: loginUrl, //接口地址
              data: { code: res.code },
              method: 'Get',
              header: { 'content-type': 'application/json' },
              success: function (res) {
                wx.setStorage({
                  key: 'third_session',
                  data: res.data.third_session,
                })
              }
            });
          }
        })
      }
    })
  }
})
onReady函数打印的日志如下:

请问是什么原因导致不一样的,我应该怎么做才能取到data中正确的数据。谢谢,感谢您的解答!
回答关注问题邀请回答
收藏

2 个回答

  • 微盟
    微盟
    2021-11-26

    https://zhuanlan.zhihu.com/p/142764985 查看下 Chrome中devtool的延迟加载,主要是基于性能考虑

    2021-11-26
    有用
    回复
  • 拾忆
    拾忆
    2020-01-09

    异步的问题~以下面实际输出为准。

    2020-01-09
    有用
    回复 3
    • 2020-01-09
      请问我需要怎么拿到正确的值尼?
      2020-01-09
      回复
    • 拾忆
      拾忆
      2020-01-09回复
      下面的值才是最终的~至于怎么处理异步覆盖的问题,你需要了解下JS的异步的基础知识。
      2020-01-09
      回复
    • 2020-01-09
      好的,谢谢您的解答!
      2020-01-09
      回复
登录 后发表内容
问题标签