我有一个时钟功能,可以获取时间并显示小时、分钟和秒,我正在尝试实时更新屏幕上的数据,但由于某种原因,我的 setInterval 功能没有达到我的预期。
我认为 React 的 render 方法应该是实时渲染数据。我需要ajax吗?谁能提供一些建议?
var CityRow = React.createClass({
render: function() {
var currentdate = new Date();
function getTime() {
// get local time based on the UTC offset
this.hours = currentdate.getUTCHours() + parseInt(this.props.UTCOffset);
// correct for number over 24, and negatives
if( this.hours >= 24 ){ this.hours = this.hours - 24; }
if( this.hours < 0 ){ this.hours = this.hours + 12; }
// add leading zero, first convert hours to string
this.hours = this.hours + "";
if( this.hours.length == 1 ){ this.hours = "0" + this.hours; }
// minutes are the same on every time zone
this.minutes = currentdate.getUTCMinutes();
// add leading zero, first convert hours to string
this.minutes = this.minutes + "";
if( this.minutes.length == 1 ){ this.minutes = "0" + this.minutes; }
this.seconds = currentdate.getUTCSeconds();
}
window.setInterval(function () {
getTime();
}, 1000);
return(
<div className="city-row" ref="cityRow">
<span className="city-time">{this.hours}:{this.minutes}:{this.seconds}</span>
</div>
</div>
)
}
});
原文由 amoeboar 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的代码似乎有几个问题。首先是渲染函数中的关闭 div,它会导致您的元素甚至无法渲染。
接下来,您可能想看看 state/props 和 React 通用生命周期方法,以更好地了解程序流程。 setInterval 应该放在 componentDidMount 中,这样它就不会在每次组件渲染和创建大量计时器时都被调用。将小时、分钟和秒作为状态也可能会有所帮助,这样当这些更改时您的组件会自动重新呈现。
我在下面修改了你的代码,并在 jsfiddle 上放了一个例子。它没有正确打印秒数(就像在您的 getTime 方法中一样),但希望它能让您更好地了解逻辑应该如何流动。
https://jsfiddle.net/rpg6t4uc/