在我的反應應用程式中,我有時會呼叫 api 呼叫,但在第一次呼叫時我沒有從 api 接收資料。在這種情況下,當我進行第二次 api 呼叫時,我總是會收到結果。如何解決問題。
useEffect(() => {
post(`get-${props.url}`, {searchParams: {UserId: props.userId}})
.then(response => {
if (Object.keys(response.data).length === 0) {
recursiveCall()
}
console.log(response, 'response')
})
.catch(error => {
console.log(error, 'error')
})
}, [ ])
uj5u.com熱心網友回復:
我在思考問題后提出了解決方案。我是我的 api 呼叫,我總是在第二次得到回應,所以我想使用遞回概念來解決問題。實施解決方案后,它按我預期的方式作業。
useEffect(() => {
let rcCount = 0
const recursiveCall = () => {
post(`get-${props.url}`, {searchParams: {UserId: props.userId}})
.then(response => {
rcCount = 1
if (Object.keys(response.data).length === 0 && rcCount < 4) {
recursiveCall()
}
console.log(response, 'response')
})
.catch(error => {
console.log(error, 'error')
})
}
recursiveCall()
}, [ ])
uj5u.com熱心網友回復:
我會首先專注于找出問題的根本原因。如果 API 是您控制的東西,我會從那里開始檢查為什么服務器只在您的第二個請求而不是第一個請求上給您回應。
如果您無法解決根本原因,那么您可能需要使用具有指數退避的重試演算法,以避免服務器因過多的請求而過載。
在您的初始解決方案指數退避之上構建將如下所示:
useEffect(() => {
const recursiveCall = (depth = 1) => {
post(`get-${props.url}`, {searchParams: {UserId: props.userId}})
.then(response => {
if (Object.keys(response.data).length === 0) {
setTimeout(() => recursiveCall(depth 1), 2 ** depth * 1000)
}
console.log(response, 'response')
})
.catch(error => {
console.log(error, 'error')
})
}
recursiveCall()
}, [ ])
// Call nr. | Delay
// 1 | 0s
// 2 | 2s
// 3 | 4s
// 4 | 8s
// ...and so on
您可能需要考慮在實用程式函式中提取退避機制,而不是將其硬編碼在useEffect掛鉤中。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/520663.html
上一篇:按給定順序排名
