从react中的finally块中返回cleanup函数



在React函数元素中,我有一个use Effect hood,它有一些基于回调的东西。在回调链的末尾,我需要在卸载时返回一个函数来清理。这是怎么做到的。

我有这样的东西:

ReactFunctionElement=(..)=>{
useEffect(()=>{
asyncCall()
.then(..)
.cath(..)
.finally(
return ()=>{cleanup stuff}
)
},[some filters])
}

但是清理的东西从来没有运行过。我不知道如何,或者是否有可能,将其重新提升到useEffect并返回。

我想你需要这样的东西:

useEffect(() => { 
// Closure variable
const thingToCleanup = null;
asyncCall()
.then(thingToCleanup = thingFromAsync...)
.catch(...);
return () => { 
// cleanup stuff using thingToCleanup
});
} ,[some filters]) }

您的useEffect函数必须返回clean up函数,.finally返回一个Promise,它不起作用,但您也不返回(JavaScript将隐式返回undefined(。但是,您需要在清理中访问设置代码中的一些变量,以便将这些变量存储在闭包中,以便稍后在清理过程中使用。

您可以订阅api调用,在cleanup函数中可以取消订阅

useEffect(() => { 
api.subscribe(userId);
return () => api.unsubscribe(userId);
}, [ userId ])

最新更新