取消componentWillUnmount中的所有订阅

时间:2018-12-11 18:15:11

标签: javascript reactjs

每5秒钟更新一次状态, 我知道我无法更新componentWillUnmount中的状态,但是当我更改页面时我无法停止更新。 离开页面后如何停止更新?

import React, { Component } from 'react';

class RandomText extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoad: true,
    }
  }
  _isMounted = false;

  componentDidMount() {
    this._isMounted = true;
    this.onLoad();
  }

  onLoad = () => {
    const { isLoad } = this.state;
    if (this._isMounted === true) {
      if (isLoad !== true) {
        setTimeout(() => { this.setState({ isLoad: !this.state.isLoad }) }, 5000)
      }
      if (isLoad === true) {
        setTimeout(() => { this.setState({ isLoad: !this.state.isLoad }) },5000)
      }
    }
  }

  componentDidUpdate(prevProps, prevState) {
    const { isLoad } = this.state;
    if (isLoad !== prevState.isLoad) {
      this.onLoad();
    }
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  render() {
    const { isLoad }=this.state;
    return (
      <div className='landing'>
        <div className='landingInfo' >

此处根据状态更改类

          <p className={isLoad ? 'classOne' : 'classTwo'}>Text here</p>
        </div>
      </div>
    )
  }
}

export default RandomText;

谢谢!

1 个答案:

答案 0 :(得分:0)

这样做

将每个setTimeout分配给一个变量,并使用如下所示的clearTimeout方法在componentWillUnMount中清除它们

    onLoad = () => {
         const { isLoad } = this.state;
         if (this._isMounted === true) {
               if (isLoad !== true) {
                    this.timeout1 = setTimeout(() => {      this.setState({ isLoad: !this.state.isLoad }) }, 5000)
                    }
               if (isLoad === true) {
                     this.timeout2 = setTimeout(() => { this.setState({ isLoad: !this.state.isLoad }) },5000)
               }
           }
       }

  componentWillUnMount(){
        this._isMounted = false;
        clearTimeout(this.timeout1);
        clearTimeout(this.timeout2);
  }