componentWillUnmount() not being called when refreshing the current page

前端 未结 3 1563
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:19

    When the page refreshes react doesn't have the chance to unmount the components as normal. Use the window.onbeforeunload event to set a handler for refresh (read the comments in the code):

    class Demo extends React.Component {
        constructor(props, context) {
            super(props, context);
    
            this.componentCleanup = this.componentCleanup.bind(this);
        }
    
        componentCleanup() { // this will hold the cleanup code
            // whatever you want to do when the component is unmounted or page refreshes
        }
    
        componentWillMount(){
          if(dataReady.get(true)){
            let logos = this.props.questions[0].data.logos.length > 0 ? this.props.questions[0].data.logos.filter((item) => {
              if(item.logo === true && item.location !== ""){
                return item;
              }
            }) : [];
    
            this.setState({ logos });
          }
        }
    
        componentDidMount(){
          window.addEventListener('beforeunload', this.componentCleanup);
        }
    
        componentWillUnmount() {
            this.componentCleanup();
            window.removeEventListener('beforeunload', this.componentCleanup); // remove the event handler for normal unmounting
        }
    
    }
    

    useWindowUnloadEffect Hook

    I've extracted the code to a reusable hook based on useEffect:

    // The hook
    
    const { useEffect, useRef, useState } = React
    
    const useWindowUnloadEffect = (handler, callOnCleanup) => {
      const cb = useRef()
      
      cb.current = handler
      
      useEffect(() => {
        const handler = () => cb.current()
      
        window.addEventListener('beforeunload', handler)
        
        return () => {
          if(callOnCleanup) handler()
        
          window.removeEventListener('beforeunload', handler)
        }
      }, [cb])
    }
    
    
    // Usage example
      
    const Child = () => {
      useWindowUnloadEffect(() => console.log('unloaded'), true)
      
      return 
    example
    } const Demo = () => { const [show, changeShow] = useState(true) return (
    {show ? : null}
    ) } ReactDOM.render( , root )
    
    
    
    

提交回复
热议问题