参考: 小程序如何在其他页面监听 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
- })
- })
- },
来源: http://www.bubuko.com/infodetail-3194920.html