首页 > 解决方案 > 如何在 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 小时?

标签: javascriptarraysreactjsdate

解决方案


使用数组并尝试推送为:

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);
  }

小提琴示例:小提琴链接


推荐阅读