我正在尝试了解如何将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的方式,那么我绝对不会坚持下去,并且会感激指导。
这种情况的答案是使用状态。非常感谢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" />
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句