[英]Why is `Promise.then` called twice in a React component but not the console.log?
[英]Console.log getting called twice in Vue js watcher
我正在嘗試為測驗創建一個計時器。 計時器是從 API 輸出中獲得的,以秒為單位。 我正在使用 Vuex 來存儲 API 的結果。 並使用 getter 來獲取 Timer 組件中存儲的計時器。 一旦我以秒為單位獲得計時器值,我將它轉換為計算屬性中的 hrs、min 和 sec,然后我嘗試將計時器減少 1 秒。 不知何故,我設法使用 watcher 屬性減少了計時器,但問題是計時器沒有減少 -1,而是減少了 -2。 當我在觀察者中使用 console.log 時,我注意到 console.log 被調用了兩次。 一次使用未定義的計時器值,一次使用計時器的實際值。 我不知道我是否以正確的方式做這件事,因為我是 Vuejs 的新手。 請幫我解決這個問題,並糾正我的錯誤。 我將附上我迄今為止嘗試編寫的代碼。
謝謝。
const Timer = Vue.component('Timer', {
template: `
<div class="navbar-nav ml-auto" v-if="time_left">
{{hour}} : {{min}} : {{sec}}
</div>
`,
computed: {
...Vuex.mapGetters([
'time_left'
]),
hour(){
let h = Math.floor(this.time_left / 3600)
return h > 9 ? h : '0' + h;
},
min(){
let m = Math.floor(this.time_left % 3600 / 60);
return m > 9 ? m :'0' + m
},
sec(){
let s = Math.floor(this.time_left % 3600 % 60);
return s > 9 ? s : '0' + s
}
},
watch: {
time_left: {
immediate: true,
handler (newVal) {
const timer = this.time_left
setInterval(() => {
// this.$store.commit('UPDATE_QUIZ_TIMER', this.time_left)
console.log(this.time_left)
}, 1000)
}
}
}
})
你沒有做錯任何事。 當屬性第一次被定義為undefined
值時,watcher 被觸發一次,然后當一個值被分配給它時被觸發兩次。 嘗試:
watch: {
time_left: {
immediate: true,
handler (newVal) {
if(newVal !== undefined){
const timer = this.time_left
setInterval(() => {
// this.$store.commit('UPDATE_QUIZ_TIMER', this.time_left)
console.log(this.time_left)
}, 1000)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.