• [React] Setup 'beforeunload' listener


    In this lesson we'll show how to take a beforeUnload call and convert it to a declarative React Component. It will handle subscribing to events, and automatically unsubscribing to prevent memory leaks.

    class BeforeUnload extends React.Component {
    
      constructor(props) {
        super(props);
        this.alertMessage = this.alertMessage.bind(this);
      }
    
      componentDidMount() {
        window.addEventListener("beforeunload", this.alertMessage);
      }
      
      componentDidUpdate(prevProps, prevState) {
        const { active } = this.props;
        const { active: wasActive } = prevProps;
    
        if (wasActive && !active) {
          window.removeEventListener("beforeunload", this.alertMessage);
        } else if (!wasActive && active) {
          window.addEventListener("beforeunload", this.alertMessage);
        }
      }
      
      componentWillUnmount() {
        window.removeEventListener("beforeunload", this.alertMessage);
      }
    
      alertMessage(e) {
        if (this.props.active) {
          e.returnValue = true;
          return true;
        }
      }
      
    
      render() {
        return this.props.children;
      }
    }
    
    class App extends React.Component {
      
      constructor(props) {
        super(props);
        this.state = {
          active: true,
        }
        this.toggle = this.toggle.bind(this);
      }
      
      toggle() {
        this.setState((state) => { 
            return { active: !state.active } 
          }
        );
      }
      
      render() {
        return (
          <BeforeUnload active={this.state.active}>
            <button onClick={this.toggle}>{this.state.active ? "Active": "Inactive"}</button>
          </BeforeUnload>
        );
      }
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById('example')
    );

  • 相关阅读:
    安全探讨之用Win32汇编写双进程守护
    LightTPD 1.4.12
    mysql4存在mysql5没有的性能成绩
    gcolor2-拾色器
    solaris 中挂载usb移动硬盘
    Browsershots:测试你的 Web 企图
    MythTV 0.20
    XorgEdit:xorg.conf 编纂器
    pci168c,1c无线网卡如何在64位Solaris系统上运用
    Fedora8中批改磁盘卷标
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6973154.html
Copyright © 2020-2023  润新知