javascript - 在 ReactJS 中清除 setInterval()

标签 javascript reactjs

我正在我的 ReactJS 应用程序中创建一个 setInterval,我需要稍后在组件卸载时清除它。因此,我无法使用我使用的以下代码来实现此目标:

    var Timer = React.createClass ({

  getInitialState: function () {
    return ({
      timeLeft: "99:99:99"
    })
  },

  componentDidMount: function () {

    var compteur = setInterval( function () {
      var heure = new Date();
      var timeH = ((0 + this.props.endH - heure.getHours()) > 9) ? (0 + this.props.endH - heure.getHours()) : ("0" + (0 + this.props.endH - heure.getHours())) ;
      var timeM = ((0 + this.props.endM - heure.getMinutes()) > 9) ? (0 + this.props.endM - heure.getMinutes()) : ("0" + (0 + this.props.endM - heure.getMinutes())) ;
      var timeS = ((0 + this.props.endS - heure.getSeconds()) > 9) ? (0 + this.props.endS - heure.getSeconds()) : ("0" + (0 + this.props.endS - heure.getSeconds())) ;

      this.setState({
        timeH: timeH,
        timeM: timeM,
        timeS: timeS
      });

      this.setState ({
        timeLeft: this.state.timeH + ":" + this.state.timeM + ":" + this.state.timeS
       })

    }.bind(this), 900);

    compteur;

  },

  componentWillUnmount: function () {
    console.log("Unmounting Timer...");
    clearInterval(this.compteur);
    this.compteur = false;
  },

  render: function() {
    return (
      <div className="time-count">{this.state.timeLeft}</div>
    )
  }

});

问题是,当我尝试通过 clearInterval(compteur) 设置间隔后立即清除它时,它起作用了。但当我稍后尝试使用 clearInterval(this.compteur) 执行此操作时,情况并非如此。

谢谢!

最佳答案

当您像这样声明 compteur 时,您是在告诉这是一个范围在 componentDidMount 函数中的普通变量。

直接替换即可

var compteur = setInterval( function () {

this.compteus = setInterval( function () {

您将能够从 componentWillUnmount 函数访问 this.compteur

工作演示:https://jsfiddle.net/mrlew/bfexkpkx/

关于javascript - 在 ReactJS 中清除 setInterval(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42181361/

相关文章:

javascript - 如何从html Action 中显示js消息

javascript - WebGl - 只能绘制一个对象

reactjs - 找不到所需的 `intl` 对象。 <IntlProvider> 需要存在于组件祖先中

javascript - 无法将 react 组件方法作为 prop 回调提供给另一个功能组件

reactjs - componentDidUpdate prevProps 给我当前/新的 Prop

javascript - AngularJS - 预加载应用程序设置

javascript - Uncaught ReferenceError : tinymce is not defined

javascript - 在子组件的 ngAfterViewInit() 中调用时,父组件的元素上的 getElementById 返回 null

javascript - 在expressjs上动态转译和服务React应用程序

reactjs - 使用 React 路由器的站点中的 Slash 问题