在做小程序的時(shí)候,做到了一個(gè)限時(shí)商品售賣,用到了倒計(jì)時(shí),因?yàn)檫@個(gè)原因?qū)е铝税沧渴謾C(jī)上使用小程序時(shí),將小程序放入后臺(tái)運(yùn)行一段時(shí)間后,再次進(jìn)入小程序后出現(xiàn)了頁(yè)面白屏或者點(diǎn)擊事件失效的情況,這里記錄下
我這里是使用了自定義組件的形式來(lái)渲染的
/* limitCommodity是一個(gè)數(shù)組,返回的是商品對(duì)象,包含商品價(jià)格、商品結(jié)束時(shí)間、商品圖片等 */ <block wx:for="{{limitCommodity}}" wx:key="{{item.id}}"> <commodityItem class="specialContent" goods="{{item}}" /> </block> 自定義組件的js文件 Component({ properties: { goods: Object }, data: { }, timer: null, /* 在組件實(shí)例進(jìn)入頁(yè)面節(jié)點(diǎn)樹時(shí)執(zhí)行,開始定時(shí)器 */ attached: function() { if(this.timer) { clearInterval(this.timer); } this.filterTime(); let that = this; this.timer = setInterval(function () { that.filterTime(); }, 1000) }, /* 在組件實(shí)例被從頁(yè)面節(jié)點(diǎn)樹移除時(shí)執(zhí)行,將定時(shí)器清除 */ detached: function() { clearInterval(this.timer); this.timer = null; }, methods: { /* 用于將時(shí)間戳轉(zhuǎn)換成自定義的時(shí)間格式 */ filterTime() { let totalTime = new Date(parseInt(this.data.goods.endtime) * 1000) - new Date(); let days = parseInt(totalTime / 1000 / 60 / 60 / 24, 10); let hours = parseInt(totalTime / 1000 / 60 / 60 % 24, 10); let minutes = parseInt(totalTime / 1000 / 60 % 60, 10); let seconds = parseInt(totalTime / 1000 % 60, 10); let day = days >= 10 ? days : '0' + days; day = day == 0 ? '' : day + '天'; let hour = hours >= 10 ? hours : '0' + hours; let minute = minutes >= 10 ? minutes : '0' + minutes; let second = seconds >= 10 ? seconds : '0' + seconds; this.setData({ limitTime: day + hour + ":" + minute + ":" + second }) }, } }) |
改進(jìn)方法就是減少setData操作
Component({ properties: { limitCommodity:Array }, data: { }, timeOut:null, /* 在組件實(shí)例進(jìn)入頁(yè)面節(jié)點(diǎn)樹時(shí)執(zhí)行 */ attached(){ this.calculate(); }, /* 在組件實(shí)例被從頁(yè)面節(jié)點(diǎn)樹移除時(shí)執(zhí)行,將定時(shí)器清除 */ detached(){ clearTimeout(this.timeOut); this.timeOut = null; }, methods: { filterTime(endtime) { let totalTime = new Date(parseInt(endtime) * 1000) - new Date(); let days = parseInt(totalTime / 1000 / 60 / 60 / 24, 10); let hours = parseInt(totalTime / 1000 / 60 / 60 % 24, 10); let minutes = parseInt(totalTime / 1000 / 60 % 60, 10); let seconds = parseInt(totalTime / 1000 % 60, 10); let day = days >= 10 ? days : '0' + days; day = day == 0 ? '' : day + '天'; let hour = hours >= 10 ? hours : '0' + hours; let minute = minutes >= 10 ? minutes : '0' + minutes; let second = seconds >= 10 ? seconds : '0' + seconds; return day + hour + ":" + minute + ":" + second }, calculate(){ let limitCommodity = this.data.limitCommodity; for (let i = 0; i < limitCommodity.length;i++){ limitCommodity[i]['endtime_date'] = this.filterTime(limitCommodity[i]['endtime']) } this.setData({ limitCommodity }) this.timeOut = setTimeout(()=>{ this.calculate(); },1000); } } }) |
正在努力學(xué)習(xí)中,若對(duì)你的學(xué)習(xí)有幫助,留下你的印記唄(點(diǎn)個(gè)贊咯^_^)
工作日 8:30-12:00 14:30-18:00
周六及部分節(jié)假日提供值班服務(wù)