How to properly use componentWillUnmount() in ReactJs

前端 未结 4 1150
谎友^
谎友^ 2020-12-23 19:18

From the official tutorial:

componentWillUnmount() is invoked immediately before a component is unmounted and destroyed. Perform any nece

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-23 19:47

    In this simple example (example taken from React Docs) I am using it for clearing interval of a Clock component. For example in your page you have 2 tabs, one of them is showing User Info and second tab is User Schedule which shows a live clock over there. Once you switch to User Schedule tab, componentDidMount will be called to set the timer. And once you switch back to User Info, there is no need to keep this interval hook and you can write your unbind/unsubscribe logic in componentWillUnmount event.

    import React from "react";
    export default class Clock extends React.Component {
      constructor(props) {
        console.log("Clock", "constructor");
        super(props);   
        this.state = {
          date: new Date()
        };
      }
      tick() {   
        this.setState({
          date: new Date()
        });
      }
      // These methods are called "lifecycle hooks".
      componentDidMount() {
        console.log("Clock", "componentDidMount");
        this.timerID = setInterval(() => {
          this.tick();
        }, 1000);
      }
      // These methods are called "lifecycle hooks".
      componentWillUnmount() {
        console.log("Clock", "componentWillUnmount");
        clearInterval(this.timerID);
      }
      render() {
        return (        
            
    It is {this.state.date.toLocaleTimeString()}.
    ); } }

提交回复
热议问题