javascript - 如何在 ReactJS 中创建最近几个小时的数组?
问题描述
我的反应应用程序需要最近 12 个小时的数组,但到目前为止我只有 2 个,而且我正在以最乏味的方式进行操作。
这是我当前有效的代码:
class Example extends Component {
constructor() {
super();
this.now = new Date();
this.hrAgo = new Date(this.now-3600000).toISOString();
this.twoHrsAgo = new Date(this.now-2*3600000).toISOString();
this.state = {
timeData: [this.twoHrsAgo,this.hrAgo,this.now.toISOString()]
}
}
componentDidMount() {
console.log("timeData: ",this.state.timeData);
};
/// other function below
在我的控制台中显示如下内容:
["2019-05-08T06:19:41.744Z", "2019-05-08T07:19:41.744Z", "2019-05-08T08:19:41.744Z"]
如何以更好的方式获得最后 12 小时?
解决方案
使用数组并尝试推送为:
constructor() {
super();
this.now = new Date();
let testArr= [];
for(let i=0;i<12;i++){
testArr.push(new Date(this.now-i*3600000).toISOString());
}
this.state = {
timeData: testArr
}
}
componentDidMount() {
console.log("timeData: ",this.state.timeData);
}
小提琴示例:小提琴链接
推荐阅读
- clickhouse - 为什么 clickhouse 'DESCRIBE TABLE' 返回 4 或 5 列
- blazor - 无法使用 VS 2019 预览版和 3.0 SDK 运行 Blazor
- python - 给定 2 个排序列表 A 和 B,找到 B 中不在 A 中的所有元素
- sql - Postgres选择时间范围之前和之后是否存在另一个事件
- matlab - 将数组的负数替换为 77 的函数
- c++ - 资格转换的歧义
- reactjs - 在 Reactjs 中使用 OData 进行计数
- kotlin - 如何在 Kotlin 中实现方法上的互斥锁并将一个线程优先于另一个线程?
- makefile - 如何为来自不同路径的源编写构建目标?
- json - 需要 Nan 键:将 PySpark DF 写为 Json 时的值