问题描述:
微信小程序需要在 app.js 里面去进行用户静默登录等操作,然后首页又需要根据后台返回的用户信息进行请求,那么这个时候问题就来了,可能首页的请求先于 app.js ,那么就会因为获取不到用户信息而报错!
解决办法一 定时器
解决思路:
用一个100ms的定时器去重复确认是否有用户信息,没有就继续确认,有了就清除定时器并进行请求
代码:
this.data.timer = setInterval(() => {
if(app.globalData.userInfo?.id) {
clearInterval(this.data.timer);
wx.request({
url:"xxxxx",
method:"POST",
data: {
userId: app.globalData.userInfo.id,
orgId: app.globalData.orgId,
}
}).then( res => {
if(res.status == 200){
console.log(res);
} else {
wx.showToast({
title: res.msg,
icon: 'error',
duration: 2000,
mask:true
})
}
}).catch( err => {
console.log(err);
})
}
}, 100)
注意:
1、这里还有一个变化的,就是设置一个变量,只有请求到了用户信息,再赋值为 true ,首页还是循环去判断这个变量,其实一样的!
2、记得 onHide 的时候也要清除定时器!
解决办法二 官方
解决思路:
通过 app.js 直接去调取首页的请求!具体思路就是,如果首页能获取到用户id,就直接在首页进行请求,如果获取不到,就通 app.方法名 给app里面的方法赋值成为请求,然后在登录接口的 then 中调用该方法!
代码:
app.js
wx.login({
success: res => {
let data = {
jsCode: res.code,
appId: getApp().globalData.appId,
}
wx.request({
url: 'xxxxx',
data: data,
})
.then(result => {
if (result.status == 200) {
getApp().globalData.userInfo = res.obj
this.pageFun(); // 首页方法
} else {
wx.showToast({
title: result.msg
})
}
})
}
})
首页.js
if(app.globalData.userInfo?.id) {
wx.request({
url:"xxxxx",
method:"POST",
data: {
userId: app.globalData.userInfo.id,
orgId: app.globalData.orgId,
}
}).then( res => {
if(res.status == 200){
console.log(res);
} else {
wx.showToast({
title: res.msg,
icon: 'error',
duration: 2000,
mask:true
})
}
}).catch( err => {
console.log(err);
})
} else {
app.pageFun = wx.request({
url:"xxxxx",
method:"POST",
data: {
userId: app.globalData.userInfo.id,
orgId: app.globalData.orgId,
}
}).then( res => {
if(res.status == 200){
console.log(res);
} else {
wx.showToast({
title: res.msg,
icon: 'error',
duration: 2000,
mask:true
})
}
}).catch( err => {
console.log(err);
})
}
注意
菜鸟暂时只知道这两种方法,后面有别的再来补充,这里第二种我没有写代码,现场搞的,可能有点问题,但是知道思路,相信读者不用看我的就可以自己写出来!
微信小程序图片不显示
一、图片命名用了中文,或者路径有中文
一般程序员是遇不见的,这也是菜鸟一时图简单,所以才出现了这个bug,毕竟菜鸟的英语不好!
二、写的是相对路径而不是根路径
相对路径:
<view class='seat-size' wx:for="{{item}}" wx:key="index" wx:for-index="index" wx:for-item="citem">
<image src='../../../images/seaticon.png' class='seat-img' />
</view>
根路径:
<image src='/images/seaticon.png' class='seat-img' />
注意:
菜鸟发现,现在这个似乎要求不严格,不会产生加载不出图片的现象!
三、其它
1、图片名称去除空格
2、网络图片,图片的 HTTP/HTTPS 应为小写的 http/https 以及图片的后缀为小写的.png或者.jpg
注意:
如果http显示不了,可以尝试改成https,该篇博客 是这样说的:
3、域名已备案
四、微信小程序背景图片
最近菜鸟上班了,然后正好做微信小程序需要有背景图,之前没搞过つ﹏⊂
这里就要注意两点:
1、背景图片不能在wxss里面写!
参考:微信小程序 wxss 背景图 本地资源图片无法通过 WXSS 获取,可以使用网络图片,或者 base64
2、背景图写在style里面,用相对路径、绝对路径真机调试都不显示(电脑显示)!所以最好的办法就是用image标签,然后定位成背景图片!!!