![](/img/trans.png)
[英]Catch the error from an async function in react application globally
[英]React redux application run one function globally
我嘗試檢測瀏覽器或選項卡已關閉。 在整個大型應用程序中運行一個功能的最佳方式是什么?
window.onbeforeunload = function () {
return "Do you want to close?";
};
你可以使用 react hook 並在你的 App.js 中實現它。我稱之為 useBeforeUnload :D
import { useEffect } from 'react'
const useBeforeUnload = (
value: ((evt: BeforeUnloadEvent) => any) | string
) => {
const handleBeforeunload = (evt: BeforeUnloadEvent) => {
let returnValue
if (typeof value === 'function') {
returnValue = value(evt)
} else {
returnValue = value
}
if (returnValue) {
evt.preventDefault()
evt.returnValue = returnValue
}
return returnValue
}
useEffect(() => {
window.addEventListener('beforeunload', handleBeforeunload)
return () => window.removeEventListener('beforeunload', handleBeforeunload)
}, [])
}
export default useBeforeUnload
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.