HarmonyOS 鸿蒙Next 想请问为什么加了定时循环但文本时间还是不变呀?

HarmonyOS 鸿蒙Next 想请问为什么加了定时循环但文本时间还是不变呀?

import router from '@ohos.router'
import systemDateTime from '@ohos.systemDateTime'
import securityLabel from '@ohos.file.securityLabel'

export default {
    data: {
        sec: "",
        ms: "",
        hour: "",
        min: "",
    },
    onShow() {
        this.getDate();
    },

    getDate: function () {
        let newDate = new Date();

        this.sec = newDate.getSeconds();
        this.hour = newDate.getHours();
        this.min = newDate.getMinutes();
        
    },
    setInterval() {
         setInterval(function(){
            this.getDate();
        }, 1000);
    },
    onclick: function () {
        router.push({
            url: "pages/sear/sear"
        })
    }
}

更多关于HarmonyOS 鸿蒙Next 想请问为什么加了定时循环但文本时间还是不变呀?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

11 回复

两个问题:

1)this指向问题,如2楼的半夏所说,需要在第一层函数中传递下this进第二层函数:let this_=this;

2)setInterval未激活,把onShow函数中的this.getDate()换成this.setInterval()就可以了。

export default {
    data: {
        sec: "",
        ms: "",
        hour: "",
        min: "",
    },

    getDate: function () {
        let newDate = new Date();

        this.sec = newDate.getSeconds();
        this.hour = newDate.getHours();
        this.min = newDate.getMinutes();

    },
    onShow(){
      this.setInterval();
    },
    setInterval(){
        let that=this;
        setInterval(function (){
           that.getDate();
        },1000)
    }
}

更多关于HarmonyOS 鸿蒙Next 想请问为什么加了定时循环但文本时间还是不变呀?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


真的特别感谢!您人真的巨好!!!

setInterval() {
    let this_ = this;
    setInterval(function() {
        this_.getDate();
    }, 1000);
},

可以百度了解下 js的this指向

HarmonyOS的社区里有很多技术大牛分享经验,学到了很多有用的知识。

好的谢谢!!!!这就去,

有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html

看一下你调用的时候指向有没有问题

还有把hml贴出来看一下

北京时间  
`{{hour}}:{{min}}:{{sec}}`  
[搜索](#)

还想知道什么叫调用的时候指向有没有问题T-T,

你没学过JS吗… https://www.runoob.com/js/js-this.htmlh ±$%-+ 简单来说,我怀疑你在setInterval里调用的this指向并不是export default出去的那个,而是setInterval这个function的内部,因为匿名函数使用this指向是根据在哪里调用,

在鸿蒙Next中,如果加了定时循环但文本时间不变,可能是由于以下几个原因:

  1. 定时器未正确触发:定时器可能未按照预期的时间间隔触发,导致文本时间未更新。检查定时器的设置,确保时间间隔和触发逻辑正确。

  2. UI未刷新:即使定时器触发了,如果UI未刷新,文本时间也不会更新。确保在定时器回调中调用UI刷新方法,如invalidate()postInvalidate()

  3. 时间格式问题:时间格式可能在每次更新时未正确应用,导致文本显示的时间未变化。确保在每次更新时正确格式化时间。

  4. 数据绑定问题:如果使用了数据绑定,确保绑定的数据源在定时器触发时更新,并且UI能够正确响应数据变化。

  5. 线程问题:如果定时器在非UI线程中运行,确保在更新UI时切换到UI线程,避免UI更新失败。

检查以上几点,确保定时循环和UI更新逻辑正确,文本时间应能正常更新。

回到顶部