未使用缓冲的请求
将请求添加到小程序的生命周期函数,每次加载数据都会请求数据。
Page({
data : {
imgList: []
},
onLoad: function() {
carouselModel.getAll((res) => {
let imgList = res.object;
this.setData({ imgList });
})
}
})
使用缓冲之后
每次加载页面都会发送请求,很多不经常需要加载的数据频繁的请求服务器很浪费资源。将数据添加在小程序的缓冲中,可以节省很多不必要的数据请求。
封装小程序的缓冲api接口函数
class TimeStorage {
constructor() {
this.deepTime = "_deepTime";
}
putStorage(k, v, t = 0) {
wx.setStorageSync(k, v);
if (t > 0) {
let timestamp = Date.parse(new Date());
timestamp = timestamp / 1000 + parseInt(t);
console.log("添加失效时间");
console.log(timestamp);
wx.setStorageSync(k + this.deepTime, timestamp.toString());
}
}
getStorage(k) {
let timeNow = Date.parse(new Date()) / 1000;
let loseTime = parseInt(wx.getStorageSync(k + this.deepTime));
console.log("获取失效时间");
console.log(loseTime);
console.log("获取当前时间");
console.log(timeNow);
if (loseTime) {
if (loseTime > timeNow) {
let res = wx.getStorageSync(k);
return res ? res : '';
}else {
this.removeStorage(k);
return '';
}
}else {
let res = wx.getStorageSync(k);
return res ? res : '';
}
}
removeStorage(k) {
wx.removeStorage({key: k});
wx.removeStorage({key: k + this.deepTime});
}
clearStorage() {
wx.clearStorage();
}
}
export { TimeStorage }
使用
import { CarouselModel } from "../../models/CarouselModel.js"
import { TimeStorage } from '../../utils/timeStorage.js'
let carouselModel = new CarouselModel()
let timeStorage = new TimeStorage()
Page({
data : {
imgList: []
},
onLoad: function() {
let imgListStorage = timeStorage.getStorage('carousel');
console.log(imgListStorage);
if (imgListStorage != ''){
this.setData({ imgList: imgListStorage });
}else{
carouselModel.getAll((res) => {
let imgList = res.object;
timeStorage.putStorage('carousel', imgList, 60*60*24);
this.setData({ imgList });
})
}
}
})
初次请求
再次编译小程序
|
请发表评论