Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

reactjs - componentWillUnmount() not being called when refreshing the current page

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 component). However, it works perfectly fine just navigating and routing through my website by clicking links. Refresh the current page? Not a chance.

I found out that the problem is that componentWillUnmount() doesn't trigger when I refresh the page and triggers fine clicking links and navigating my website/app.

The triggering of the componentWillUnmount() is crucial for my app, since the data that I load and process in the componentDidMount() method is very important in displaying information to users.

I need the componentWillUnmount() to be called when refreshing the page because in my componentWillMount() function (which needs to re-render after every refresh) I do some simple filtering and store that variable in a state value, which needs to be present in the logos state variable in order for the rest of the component to work. This does not change or receive new values at any time during the component's life cycle.

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: logos});
  }
};

Cliffs:

  • I do DB filtering in componentWillMount()method
  • Need it to be present in the component after refresh
  • But I have a problem where the componentWillUnmount() doesn't trigger when the page is refreshed
  • Need help
  • Please
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 <div>example</div>
}

const Demo = () => {
  const [show, changeShow] = useState(true)

  return (
    <div>
      <button onClick={() => changeShow(!show)}>{show ? 'hide' : 'show'}</button>
      {show ? <Child /> : null}
    </div>
  )
}

ReactDOM.render(
  <Demo />,
  root
)
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...