javascript - React 应用程序中的 setInterval

标签 javascript reactjs settimeout state

我对 React 还是相当陌生,但我一直在慢慢磨合,我遇到了一些让我卡住的东西。

我正在尝试在 React 中构建一个“计时器”组件,老实说,我不知道我这样做是否正确(或有效)。在下面的代码中,我将状态设置为返回一个对象 { currentCount: 10 } 并且一直在玩弄 componentDidMountcomponentWillUnmountrender 并且我只能让状态从 10 到 9“倒计时”。

两部分问题:我错了什么?而且,是否有更有效的方法来使用 setTimeout(而不是使用 componentDidMount & componentWillUnmount)?

提前谢谢你。

import React from 'react';

var Clock = React.createClass({

  getInitialState: function() {
    return { currentCount: 10 };
  },

  componentDidMount: function() {
    this.countdown = setInterval(this.timer, 1000);
  },

  componentWillUnmount: function() {
    clearInterval(this.countdown);
  },

  timer: function() {
    this.setState({ currentCount: 10 });
  },

  render: function() {
    var displayCount = this.state.currentCount--;
    return (
      <section>
        {displayCount}
      </section>
    );
  }

});

module.exports = Clock;

最佳答案

我发现您的代码有 4 个问题:

  • 在您的计时器方法中,您始终将当前计数设置为 10
  • 你尝试在 render 方法中更新状态
  • 您不使用setState 方法来实际更改状态
  • 您没有将 intervalId 存储在状态中

让我们尝试解决这个问题:

componentDidMount: function() {
   var intervalId = setInterval(this.timer, 1000);
   // store intervalId in the state so it can be accessed later:
   this.setState({intervalId: intervalId});
},

componentWillUnmount: function() {
   // use intervalId from the state to clear the interval
   clearInterval(this.state.intervalId);
},

timer: function() {
   // setState method is used to update the state
   this.setState({ currentCount: this.state.currentCount -1 });
},

render: function() {
    // You do not need to decrease the value here
    return (
      <section>
       {this.state.currentCount}
      </section>
    );
}

这将导致计时器从 10 减少到 -N。如果你想要计时器减少到 0,你可以使用稍微修改的版本:

timer: function() {
   var newCount = this.state.currentCount - 1;
   if(newCount >= 0) { 
       this.setState({ currentCount: newCount });
   } else {
       clearInterval(this.state.intervalId);
   }
},

关于javascript - React 应用程序中的 setInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36299174/

相关文章:

javascript - 使用 jQuery 处理下拉列表的更改事件

laravel - 您的使用react.js 和后端的工作流程是什么样的?

javascript - 状态未使用 React redux thunk 更新

javascript - 定义之前使用的jslint settimeout

javascript - XSL 作为 javascript 函数参数

JavaScript == $0 前所未见

javascript - 使用 jQuery 即时创建嵌套 DIV

reactjs - 如何使用 react-day-picker 发布正确的工作日

javascript - 我想以一定的间隔在 Canvas 上绘制,但 setTimeout 不起作用

java - 手动超时java中的httpurlconnection