挂载公众号菜单小程序第二个页面,获取不到app.js里的全局变量?
发布于 5 年前 作者 lei90 10812 次浏览 来自 问答

小程序第二个页面挂载公众号菜单里面,获取不到app.js里的全局变量,显示为undefined?如果从第一个页面跳转到第二页面时候,可以正常获取全局变量。

4 回复

我有个问题:时间这种东西为啥要用全局变量存起来?你别的页面再用的时候,时间不是已经变了吗?别的页面直接调函数app.getserverdate()更合理吗?

app.js


onLaunch: function () {

if (!wx.cloud) {

console.error('请使用 2.2.3 或以上的基础库以使用云能力')

} else {

//云开发初始化

wx.cloud.init({

env: '',

traceUser: true

})

//const { OPENID } = cloud.getWXContext();

}

this.globalData = { serverDate: this.getserverDate()}

}


//获取服务器时间

getserverDate: function () {

wx.cloud.callFunction({

name: 'getdate',

success: function (res) {

getApp().globalData.serverDate = res.result

}

})

},

onShow: function () {

let that = this;

wx.getSystemInfo({//做iponeX的适配

success: res => {

console.log('手机信息res:' + res.model)

let modelmes = res.model;

if (modelmes.search('iPhone X') != -1) {

that.globalData.isIphoneX = true

}


}

})

第二个页面

pages上面引入

const app = getApp();


我直接挂载第二个页面,服务器时间不能从全局变量获取到,util.formatTime(new Date(app.globalData.serverDate))显示为NAN,如果是从第一个页面跳转第二页面显示都正常

你在小程序 app.js的onShow里进行 全局变量的赋值

你是不是在第一个页面才对app.js里的全局变量赋值了

回到顶部