码迷,mamicode.com
首页 > 其他好文 > 详细

[React] Setup 'beforeunload' listener

时间:2017-06-09 19:27:14      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:cto   style   dom   turn   before   leaks   sso   idt   struct   

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‘)
);

 

 

[React] Setup 'beforeunload' listener

标签:cto   style   dom   turn   before   leaks   sso   idt   struct   

原文地址:http://www.cnblogs.com/Answer1215/p/6973154.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!