简体   繁体   English

React redux 应用程序全局运行一个函数

[英]React redux application run one function globally

I try to detect browser or tab is closed.我尝试检测浏览器或选项卡已关闭。 What is the best way run one function all over the big application?在整个大型应用程序中运行一个功能的最佳方式是什么?

window.onbeforeunload = function () {
    return "Do you want to close?";
};

you can use react hook and implement it in your App.js .I call it useBeforeUnload :D你可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM