reactjs event listener beforeunload added but not removed

前端 未结 2 492
说谎
说谎 2020-12-02 14:16

I have a react component like :

import React, { PropTypes, Component } from \'react\'


class MyComponent extends Component {

    componentDidMount() {
             


        
2条回答
  •  一向
    一向 (楼主)
    2020-12-02 14:54

    Ori's solution didn't work for me. I had to do this to make it work... (Thank you docs)

      componentDidMount() {
        window.addEventListener('beforeunload', this.handleLeavePage);
      }
    
      componentWillUnmount() {
        window.removeEventListener('beforeunload', this.handleLeavePage);
      }
    
      handleLeavePage(e) {
        const confirmationMessage = 'Some message';
        e.returnValue = confirmationMessage;     // Gecko, Trident, Chrome 34+
        return confirmationMessage;              // Gecko, WebKit, Chrome <34
      }
    

提交回复
热议问题