JSFiddle - React, Tailwind, and code Playground
by varzy
JavaScript
// app.js
App({
globalData: {
isUserInfoInited: false,
userInfoListeners: [],
userInfo: {},
hasPhone: false,
isRegistered: false
},
onLaunch() {
this.initUserInfo();
},
async initUserInfo() {
// xxxxx = 你自己的逻辑,可以同步可以异步
const { userInfo, isRegistered, hasPhone } = await xxxxx();
this.globalData.userInfo = userInfo;
this.globalData.isRegistered = isRegistered;
this.globalData.hasPhone = hasPhone;
// 用户信息初始化完毕
this.globalData.isUserInfoInited = true;
this.globalData.userInfoListeners.forEach(listener => {
listener({
userInfo: this.globalData.userInfo,
hasPhone: this.globalData.hasPhone,
isRegistered: this.globalData.isRegistered
});
});
this.globalData.userInfoListeners = [];
},
// 页面中需要获取用户数据时,就用这个方法包裹一下
getUserInfo() {
if (this.globalData.isUserInfoInited) {
cb({
userInfo: this.globalData.userInfo,
hasPhone: this.globalData.hasPhone,
isRegistered: this.globalData.isRegistered
});
} else {
this.globalData.userInfoListeners.push(userInfoSchema => cb(userInfoSchema));
}
}
})
// page.js
const app = getApp();
Page({
onLoad() {
app.getUserInfo(({ userInfo, isRegistered }) => {
// userInfo 一定有值
})
}
})