我用JavaScript制作了一个时钟类,但它'导入时工作不正常.我只能得到秒,而时间间隔却没有;似乎也不起作用


import React, { Component } from 'react';
import { Text, View } from 'react-native';

export default class Clock extends Component {
componentDidMount(){
setInterval(() => (
this.setState(
{ curHours :  new Date().getHours()}
),
this.setState(
{ curMins :  new Date().getMinutes()}
),
this.setState(
{ curSeconds :  new Date().getSeconds()}
)
), 1000);
}

state = {curHours:new Date().getHours()};
state = {curMins:new Date().getMinutes()};
state = {curSeconds:new Date().getSeconds()};
renderHours() {
return (
<Text>{'Hours:'}{this.state.curHours}</Text>
);
}
renderMinutes() {
return (
<Text>{'Minutes:'}{this.state.curMinutes}</Text>
);
}
renderSeconds() {
return (
<Text>{'Seconds:'}{this.state.curSeconds}</Text>
);
}
}

-我正在尝试制作一款可以像日常计划器一样跟踪时间的应用程序。所以我需要在应用程序运行时实时获取当前时间。例如,该应用程序应该告诉用户他们未能在给定时间内完成某项任务。我试着导出clock.js并使用它的函数,但只有renderSeconds((在工作,其他的都只显示空白。

我认为功能组件解决这个问题会简单得多,但这只是我的看法。以下是示例的链接

当您定义state三次时,只有最后一次被持久化,因为您覆盖了前一个变量。此外,您的初始状态应该在构造函数中声明。将此添加到您的课堂顶部

constructor() {
this.state = {
curHours:new Date().getHours(),
curMins:new Date().getMinutes(),
curSeconds:new Date().getSeconds(),
}
}

最新更新