【问题标题】:The useEffect returned function never called while App closes应用关闭时从不调用 useEffect 返回函数
【发布时间】:2020-12-28 12:42:28
【问题描述】:

当应用程序关闭时我正在删除一些值,并且我正在使用 useEffect 执行此操作,但它不起作用。

export default RootComponent = ()=> {

useEffect(()=> {

   return ()=> {

     // on Android 10 Galaxy A60: this function never invoked, when app closes 
     // on Android 6 Galaxy note9 clone: this function invoked, when app closes

   }

}, []);

return (
 // ...
);

} 

【问题讨论】:

    标签: reactjs react-native react-hooks


    【解决方案1】:

    在卸载组件时调用useEffect(() => {}, []) 中返回的函数。要在浏览器选项卡时调用函数,可以使用此包。 https://github.com/jacobbuck/react-beforeunload

    【讨论】:

    • 谢谢@Prime 我应该切换到组件类?
    • 我没有在 Android 上使用任何网络应用
    • 我已经更新了答案。请再次检查。
    • 如果我调用返回函数 setupBeforeUnloadListener(); 或只是在 useEffect 中,请告诉我?
    • setupBeforeUnloadListener() 应该在组件挂载时调用。它将设置事件侦听器。您可以使用当前代码。
    猜你喜欢
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多