加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

在Meteor中使用setInterval和React

发布时间:2020-12-15 09:35:09 所属栏目:百科 来源:网络整理
导读:我试图了解如何在Meteor中使用setInterval或类似的React作为计时器.我有一个具有每小时开始和结束时间的子组件,并使用moment.js来获取当前时间.如果当前时间在开始和结束时间之间,我会显示一个进度条. 我正在使用react-timer-mixin,现在我的组件看起来像这样
我试图了解如何在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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读