微信小程序填坑之旅(1)-app.js中用云开发获取openid,在其他页上用app.globaldata.openid获取为空

参考:小程序如何在其他页面监听globalData中值的变化?https://www.jianshu.com/p/8d1c4626f9a3

原因就是:app.js没执行完时,其他页已经onload了,所以取不到globalData

解决办法就是用回调函数

app.js

//app.js
App({
  globalData: { },

  onLaunch: function() {
    },
  //获取openid,由于网络延时,通常在其他页onload之后才会success,所以从其他页传回调函数cb进来。
  getopenid: function(cb) { 
    if (this.globalData.openid) {
      typeof cb == "function" && cb(this.globalData.openid)
    } else {
var that = this wx.cloud.callFunction({ name:
'login', data: {}, success: res => { //闭包函数内,可以用this,而不需要用that=this that.globalData.openid = res.result.openid typeof cb == "function" && cb(that.globalData.openid) }, fail: err => { wx.showToast({ icon: 'none', title: '获取 openid 失败,请检查 login 云函数', }) console.log('[云函数] [login] 获取 openid 失败,请检查是否有部署云函数,错误信息:', err) }, }) } }, })

在其他页面上,onload中 const app = getApp()   用app.getopenid调用app.js中的函数,并传入参数that.cb 

  onLoad: function(options) {
    //设置回调,防止小程序globalData拿到数据为null     
    let that = this;
    app.getopenid(that.cb)

  },
  cb: function(res) {
    let that = this
    console.log("write cb res", res)
    that.setData({
      openid: res
    })
  },

这样当App.js中的getopenid有返回值时,就会更新到其他页面

还可以将that.cb写成闭包函数,就不用 let that =this了

  onLoad: function(options) {
    //设置回调,防止小程序globalData拿到数据为null    
    app.getopenid(res => {
      console.log("write cb res", res)
      this.setData({
        openid: res
      })
    })
  },
原文地址:https://www.cnblogs.com/pu369/p/11514527.html