part6 模块一 任务二
在学习微信小程序 uniapp 项目时,一些函数里面的内容异步执行了,导致出来的效果有问题。
例如:
<script>
export default {
onShow() {
if (!!uni.getStorageSync('chatList')) {
// 按照以下写法,效果会有问题:实际会先执行 uni.pageScrollTo(),后执行 this.chatList = JSON.parse(uni.getStorageSync('chatList')),导致聊天页面不能置底。
this.chatList = JSON.parse(uni.getStorageSync('chatList'))
uni.pageScrollTo({
scrollTop: 999999,
duration: 0,
success: res => {
console.log('onShowScrollTopSuccess', res)
}
})
}
},
methods: {
choseImgAndSend() {
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: res => {
console.log(res)
console.log(res.tempFilePaths[0])
// 按照以下写法,效果会有问题:实际会先执行 uni.pageScrollTo(),后执行 this.chatList.push(senMsg)、this.chatList.push(resMsg),导致聊天页面不能置底。
let senMsg = {
isMe: true,
type: 'img',
content: res.tempFilePaths[0]
}
this.chatList.push(senMsg)
let resMsg = {
isMe: false,
type: 'img',
content: res.tempFilePaths[0]
}
this.chatList.push(resMsg)
uni.pageScrollTo({
scrollTop: 999999,
duration: 0,
success: res => {
console.log('chooseImageScrollTopSuccess', res)
}
})
uni.setStorageSync('chatList', JSON.stringify(this.chatList))
}
})
}
}
}
</script>
解决方法(使用 async 、await):
<script>
export default {
onShow() {
if (!!uni.getStorageSync('chatList')) {
let showFn = async () => {
let chatListFn = () => {
this.chatList = JSON.parse(uni.getStorageSync('chatList'))
}
await chatListFn()
await uni.pageScrollTo({
scrollTop: 999999,
duration: 0,
success: res => {
console.log('onShowScrollTopSuccess', res)
}
})
}
showFn()
}
},
methods: {
choseImgAndSend() {
uni.chooseImage({
count: 1,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: async res => {
console.log(res)
console.log(res.tempFilePaths[0])
// 用 async、await 。
let senMsg = {
isMe: true,
type: 'img',
content: res.tempFilePaths[0]
}
await this.chatList.push(senMsg)
let resMsg = {
isMe: false,
type: 'img',
content: res.tempFilePaths[0]
}
await this.chatList.push(resMsg)
await uni.pageScrollTo({
scrollTop: 999999,
duration: 0,
success: res => {
console.log('chooseImageScrollTopSuccess', res)
}
})
await uni.setStorageSync('chatList', JSON.stringify(this.chatList))
}
})
}
}
}
</script>
另外,如果项目报了一些其他奇奇怪怪的 error,例如:prop-types,但在项目里,我从来没写过类似 prop-types 的代码片段,那有可能是不小心 import 了什么其他东西,导致报错了,这种错误要注意哦~