반응형
새 시간 초과 속성이 통과할 때 카운트다운 타이머가 표시되지 않습니다.어떻게 고칠까요?
실패한 가져오기 요청을 처리하는 특수 구성 요소를 만들고 싶습니다.다음과 같은 방식으로 작동할 것으로 예상됩니다.
- 가져오기 요청이 실패하면 몇 초 후에 몇 번 더 시도해야 합니다.
- 이 특수 구성 요소는 다음 요청을 시작하기 위해 카운트다운 타이머를 표시해야 합니다.
그래서 나는:
가져오기 기능이 저장되어 있습니다.정상적으로 작동합니다(3초, 6초, 9초 후에 3번 요청).
import { createStore } from "vuex";
const wait = async (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
export default createStore({
state: {
error: {
isError: false,
timerSec: null
}
},
mutations: {
setError(state, payload) {
state.error = payload.error;
}
},
actions: {
async fetchProducts({ commit, dispatch }, attempt = 1) {
try {
const response = await fetch("https://fakestoreapi.com/products222");
if (!response.ok) {
throw new Error("Something went wrong");
}
} catch (e) {
console.log("Request:", attempt);
commit("setError", {
error: {
isError: true,
timerSec: attempt * 3
}
});
if (attempt >= 3) {
return;
}
await wait(attempt * 3000);
return dispatch("fetchProducts", attempt + 1);
}
}
}
});
저는 마운트에서 App.vue의 fetchProducts()를 호출합니다.App.vue에서 다음 데이터를 오류 요청 구성 요소에 전달합니다.
<template>
<error-request v-if="error.isError" :timeout="error.timerSec"></error-request>
<h1 v-else>This should be rendered if there's no errors</h1>
</template>
오류 요청 구성 요소에는 시간 초과 속성이 변경될 때 트리거되는 countDown 메서드가 있습니다.
<template>
<div>
<h1>The next attempt to fetch data will be made in:</h1>
<h2>{{ timer }}</h2>
</div>
</template>
<script>
export default {
props: ["timeout"],
data() {
return {
timer: null,
interval: null,
};
},
methods: {
countDown(sec) {
this.interval = setInterval(() => {
this.timer = sec;
if (sec === 0) {
clearInterval(this.interval);
return;
}
sec--;
}, 1000);
},
},
watch: {
timeout() {
this.countDown(this.timeout);
},
},
};
</script>
안타깝게도 카운트다운 타이머는 두 번째 요청에 한 번만 표시됩니다(3부터 1까지 카운트다운으로 첫 번째 요청을 무시하고 세 번째 요청을 무시합니다).제가 그것을 고치는 것을 도와주시겠습니까?
코드와 박스를 만들었습니다: https://codesandbox.io/s/peaceful-sinoussi-ozjkq8?file=/src/App.vue
다음 작업을 수행해야 합니다.
methods: {
countDown(sec) {
this.timer = sec;
this.interval = setInterval(() => {
this.timer--;
if (this.timer === 0) {
clearInterval(this.interval);
return;
}
}, 1000);
},
},
watch: {
timeout: {
handler() {
this.countDown(this.timeout);
},
immediate: true,
},
},
주의해야 할 두 가지 사항이 있습니다.
- 부작용을 방지하기 위해 기능 파라미터를 수정하지 마십시오(당신의 경우는
sec
매개 변수) - 처음으로 시계를 트리거해야 하므로 옵션을 추가해야 합니다.
immediate: true
언급URL : https://stackoverflow.com/questions/72849927/countdown-timer-doesnt-display-when-a-new-timeout-props-pass-how-to-fix-it
반응형
'programing' 카테고리의 다른 글
git 모든 변경 사항을 취소하고 업스트림에서 끌어옵니다. (0) | 2023.07.06 |
---|---|
C에서 문자열을 2개의 문자열로 분할하는 방법 (0) | 2023.07.06 |
FCM 등록 ID 토큰의 최대 길이는 얼마입니까? (0) | 2023.07.06 |
VBA Excel 2003에서 "내 문서" 폴더를 가져오는 언어 독립적인 방법 (0) | 2023.07.06 |
프로파일 값을 할당하는 방법은 무엇입니까? (0) | 2023.07.06 |