componentWillUnmount() not being called when refreshing the current page

前端 未结 3 1513
Happy的楠姐
Happy的楠姐 2020-12-13 13:04

I\'ve been having this problem where my code in the componentDidMount() method wasn\'t firing properly when refreshing the current page (and subsequently, the c

3条回答
  •  醉梦人生
    2020-12-13 13:33

    I also run into this problem and realised that I needed to make sure that at least 2 components will always gracefully unmount. So I finally did a High Order Component that ensures the wrapped component is always unmounted

    import React, {Component} from 'react'
    
    // this high order component will ensure that the Wrapped Component
    // will always be unmounted, even if React does not have the time to
    // call componentWillUnmount function
    export default function withGracefulUnmount(WrappedComponent) {
    
        return class extends Component {
    
            constructor(props){
                super(props);
                this.state = { mounted: false };
                this.componentGracefulUnmount = this.componentGracefulUnmount.bind(this)
            }
    
    
            componentGracefulUnmount(){
                this.setState({mounted: false});
    
                window.removeEventListener('beforeunload', this.componentGracefulUnmount);
            }
    
            componentWillMount(){
                this.setState({mounted: true})
            }
    
            componentDidMount(){
                // make sure the componentWillUnmount of the wrapped instance is executed even if React
                // does not have the time to unmount properly. we achieve that by
                // * hooking on beforeunload for normal page browsing
                // * hooking on turbolinks:before-render for turbolinks page browsing
                window.addEventListener('beforeunload', this.componentGracefulUnmount);
            }
    
            componentWillUnmount(){
                this.componentGracefulUnmount()
            }
    
            render(){
    
                let { mounted }  = this.state;
    
                if (mounted) {
                    return 
                } else {
                    return null // force the unmount
                }
            }
        }
    
    }

    Note: If like me, you are using turbolinks and rails, you might wanna hook on both beforeunload and turbolinks:before-render events.

提交回复
热议问题