React redux应用程序全局运行一个功能

问题描述 投票:0回答:1

我尝试检测浏览器或选项卡已关闭。在大型应用程序中运行一个功能的最佳方法是什么?

window.onbeforeunload = function () {
    return "Do you want to close?";
};
javascript reactjs single-page-application
1个回答
0
投票

您可以使用react钩子并在您的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
© www.soinside.com 2019 - 2024. All rights reserved.