由于微信小程序app.js页面中的onLaunch和其他js页面中的onLoad属于异步执行。有时onLaunch中会有网络请求,在等待网络返回值时,其他js页面中的onLoad已经执行了。这时就会导致onLoad中会接收到空数据,而接收不到网络返回值。为了解决上述问题,可以使用回调函数。
可分为两种情况:
一、onLaunch网络请求时间较长,index.js中的onLoad先加载完成
此时在index.js页面中,没有获取到网络返回值,common.getNewsList()[0].id返回为null,所以进入else分支,在else中定义回调函数。当onLaunch中网络请求完成,继续向下进行时,会启动回调函数,进行赋值。
二、onLaunch加载较快,onLoad中获取到网络返回值
这时执行if分支,不再定义回调函数。
//app.js
//请求信息
App({
onLaunch: function () {
var that = this;
wx.request({
url: 'https://v.juhe.cn/', //略写
data: {
x: "",
y: ""
},
success: function (res) {
console.log(res.data);
let list = [];
for (var i = 0; i < 4; i++) {
let obj = {};
obj.id = res.data.result.data[i].uniquekey;
obj.title = res.data.result.data[i].title;
obj.date = res.data.result.data[i].date;
obj.url = res.data.result.data[i].url;
obj.poster = res.data.result.data[i].thumbnail_pic_s;
list.push(obj);
}
that.globalData.newsList = list;
if(that.readyCallback){
that.readyCallback(res) //回调函数
}
}
})
},
globalData: {
userInfo: null,
newsList:[
{
id:"null",
title:"",
poster:"",
date:"",
url:""
}
]
}
})
//index.js
onLoad: function (options) {
if (common.getNewsList()[0].id!="null") //回调函数用法较为灵活,需按项目进行编写
{
//获取列表
let list = common.getNewsList();
//更新列表数据
this.setData({ newsList: list })
}else{
app.readyCallback = res =>{
//获取列表
let list = common.getNewsList();
//更新列表数据
this.setData({ newsList: list })
}
}
}
微信小程序回调函数在数据同步中的应用
微信小程序的onLaunch和onLoad异步执行可能导致数据同步问题。当onLaunch的网络请求较慢,index.js的onLoad可能先执行,这时需通过回调函数确保数据的正确传递。本文探讨两种情况:1. onLaunch请求慢,onLoad通过回调函数获取数据;2. onLaunch快速完成,直接在onLoad中处理网络返回值。
1355

被折叠的 条评论
为什么被折叠?



