标签: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