在 React 中使用 Meteor 中的 setInterval

Using setInterval in Meteor with 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 的方法,我无论如何都不会坚持使用它,希望能得到指导。

我相当确定这是 this 的问题。 this 所指的内容可能会根据调用函数的上下文而改变,这是 setTimer 的一个常见陷阱。典型的解决方案是使用 javascript 函数 bind 显式设置回调的 this 上下文。

试试这个:

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

这种场景的答案是使用状态。非常感谢 Ramsay Lanier 的帮助。

Driver = React.createClass({
  mixins: [TimerMixin],
  getInitialState: function() {
    return {progress: 0};
  },

  componentDidMount() {
    this.setInterval(this.currentTime, 1000);
  },

  currentTime: function() {
    [...]

    if (moment(now).isBetween(beginTime, endTime)) {
      progress = Math.round((currMin / totalMin) * 60, -1);
      this.setState({progress: progress});
    }
  },

render() {
  let progress = this.state.progress;

  return (
    <DriverBar current={progress} total="60" />
  );
}