【发布时间】:2021-01-29 01:38:58
【问题描述】:
在功能性反应组件中,我声明了一个名为 IsCached 的状态变量(带有 useState)。 In 包含以下可点击图片。
<img src={imgSource} alt="button images"
onClick={function()
{
var return_value = CachePDF(props.docLink)
console.log(return_value)
if (return_value === true){
SetIsCached(1)
}
else{
SetIsCached(0)
}
}
}/>
我的目标是,此按钮将调用函数 CachePDF,然后根据该函数是否成功将状态变量设置为 1 或 0。这是我的 CachePDF 函数:
export function CachePDF(url) {
caches.open('favorites').then(function(cache) {
var updateCache = cache.add(url);
updateCache.then(function() {
console.log("article was cached in favorites")
caches.open("documents").then(function(cache){
cache.delete(url).then(console.log("article removed from documents cache"))
})
return true
}).catch(function (error) {
console.log("article was not cached in favorites")
return false
})
})
}
现在我遇到的问题是 console.log(return_value) 的输出未定义,我认为这是由于异步行为而发生的。起初我以为我可以在 CachePDF 中返回一个承诺,以确保在 CachePDF 函数完成之前不会调用更改变量 IsCached 的代码。但据我了解,我需要在 CachePDF 函数中为返回的承诺定义 .then 方法,因此 .then 方法无法访问我的功能组件中的状态变量。所以我有点卡住了
【问题讨论】:
-
您的 cachePDF 函数不返回任何内容。请记住,您在代码中看到的那些
return是用于function (cache) ...函数,而不是CachePDF函数
标签: javascript reactjs