zoukankan      html  css  js  c++  java
  • 微信小程序填坑之旅(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
          })
        })
      },
  • 相关阅读:
    路径操作OS模块和Path类(全)一篇够用!
    数据可视化:绘图库-Matplotlib
    matplotlib中文显示的问题
    Microsoft Visual C++ 14.0 is required问题解决
    python习题——随机整数生成类
    python——时间模块
    怎么获取10个线程的结果再返回
    集群服务器定时任务,只运行一个定时器的设计
    分布式事务
    分布式数据库---分库分表
  • 原文地址:https://www.cnblogs.com/pu369/p/11514527.html
Copyright © 2011-2022 走看看