【问题标题】:How to create an array of the last few hours in ReactJS?如何在 ReactJS 中创建最近几个小时的数组?
【发布时间】:2019-05-08 08:26:09
【问题描述】:

我的 react 应用程序需要最近 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 小时?

【问题讨论】:

    标签: javascript arrays reactjs date


    【解决方案1】:

    使用数组并尝试推送为:

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

    小提琴示例:Fiddle link

    【讨论】:

    • 这行得通!但它的方向是错误的。我使用 unshift() 而不是 push()
    • 如果你想要反向,只需将循环更改为 for(let i=11; i>=0;i--)
    【解决方案2】:

    您可以使用 map 来创建数组。 new Array(12) 创建空并用空字符串填充它。

    const now = new Date();
    const hourArray = new Array(12).fill("").map((v, i) => (new Date(now - 3600000*i)).toISOStrting())
    

    【讨论】:

    • 这个TemperatureChart.jsx:62 Uncaught TypeError: (intermediate value).toISOStrting is not a function出错了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-15
    相关资源
    最近更新 更多