在Meteor中使用setInterval和React

我试图了解如何在Meteor中使用setInterval或类似的React作为计时器.我有一个具有每小时开始和结束时间的子组件,并使用moment.js来获取当前时间.如果当前时间在开始和结束时间之间,我会显示一个进度条.

我正在使用react-timer-mixin,现在我的组件看起来像这样.

Driver = React.createClass({
  mixins: [TimerMixin],
  componentDidMount: function(){
    // componentDidMount is called by react when the component
    // has been rendered on the page. We can set the interval here:
    this.setInterval(this.currentTime, 15000);
  },

  currentTime: function() {
    //  Get the start time.
    var beginTime = moment(this.props.driver.startTime,"hh:mm");
    // Add an hour for end time.
    var endTime = moment(beginTime).add(1,'hours');
    // Get the current time.
    var now = moment();
    // Get total minutes between start and end.
    totalMin = endTime.diff(beginTime);
    // Get elapsed minutes.
    currMin = now.diff(beginTime);
    // Determine where we are in the schedule.
    if (moment(now).isBetween(beginTime, endTime)) {
      progress = Math.round((currMin / totalMin) * 60, -1);
      console.log(progress);
      return progress;
    }
    else {
      // Show this schedule as done.
      return 60
    }
  }, 

  // A bunch of other functions

  render() {
    return (
      <DriverBar current={this.currentTime()} total="60" />
    );
  }
});

我确定currentTime函数在setInterval中运行,因为在浏览器控制台日志中每15秒更新一次,因为我现在在我的函数中有这个.但是,我无法在组件中获取更新的进度值.它显示初始进度值,但不会使用setInterval更新.我只是在< DriverBar />中调用了错误的东西吗?

此外,如果这不是React或Meteor的方式来做到这一点,无论如何我都不会坚持它并且会欣赏方向.

最佳答案 我很确定这是一个问题.这引用的内容可以根据调用函数的上下文而改变,这是setTimer的常见缺陷.典型的解决方案是使用javascript函数bind为回调显式设置此上下文.

试试这个:

this.setInterval(this.currentTime.bind(this), 15000);
点赞