
[英]getting error : Argument of type '() => () => boolean' is not assignable to parameter of type 'EffectCallback'
[英]Argument of type '() => () => Promise<void>' is not assignable to parameter of type 'EffectCallback'
我的代码是:
useEffect(() => {
document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
window.$crisp.push(['do', 'chat:hide']);
return async () => {
window.$crisp.push(['do', 'chat:show']);
document.querySelector('body').style['background-color'] = '#ffffff';
if (router.query.id) {
const resDoc = await firebase.firestore().doc(`documents/${router.query.id}`).get();
if (resDoc.exists) {
await clearDocPrediction(router.query.id);
}
}
};
}, []);
现在我回来的原因是因为我相信它会在卸载时执行 function 清理,所以我需要保留它。 这是某种构建错误,我不太确定如何解决。 任何帮助将不胜感激。
useEffect
回调应该有返回类型 void。 所以你不能返回 Promise:
useEffect(() => {
document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)';
window.$crisp.push(['do', 'chat:hide']);
window.$crisp.push(['do', 'chat:show']);
document.querySelector('body').style['background-color'] = '#ffffff';
if (router.query.id) {
firebase.firestore()
.doc(`documents/${router.query.id}`)
.get()
.then((resDoc) => {
if (resDoc.exists) {
clearDocPrediction(router.query.id);
}
});
}
}, []);
效果的回调 function 应该返回void
,例如:
useEffect(() => { // callback; it returns void
console.log("Hi")
}, [])
或者
它应该返回() => void
类型的“清理” function ,例如:
useEffect(() => {
console.log("Hi")
return () => { // cleanup function of type : () => void
console.log("Cleanup")
}
}, [])
您收到错误是因为您的代码中的清理 function 不是() => void
类型,而是() => Promise<void>
类型,例如:
'() => () => Promise' 类型的参数不可分配给'EffectCallback' 类型的参数。 类型 '() => Promise' 不可分配给类型 'void | 破坏者”。
useEffect(() => {
console.log("Hi")
return async () => { // WRONG
console.log("Cleanup")
}
}, [])
因此,您可以通过以下方式重构“清理” function 来修复它:
return () => { // Remove async from here
const clear = async () => { // Create a new async function: clear
// write your cleanup code here
};
clear() // Call the clear() function
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.