首页 > 解决方案 > Concat Dates Array 正在更改数组最后一个索引中的日期

问题描述

我已经实现了一个函数来获取一个日期对象和一个计数作为参数,并从传递的“日期”到“计数”次返回一个日期对象数组。但是,问题出现在我正在编写的下一段代码中,最初,我使用该函数生成了一个日期数组,然后再次单击按钮,我试图将初始数组的最后一个日期传递给该函数并将新返回的数组连接到初始数组。问题是每当我将初始数组的最后一个日期传递给函数时,初始数组的最后一个索引中的日期都会更改为新数组的第一个索引的日期。我仍然无法解决这个问题。这就是我所拥有的。

const getDatesArray = (fromDate: Date, howManyDays: number) => {
  const tempDate = fromDate;
  const datesArray: Date[] = [];
  for (let i = 0; i < howManyDays; i++) {
    if (i === 0) {
      datesArray.push(new Date(tempDate.setDate(tempDate.getDate() + 0)));
    } else {
      datesArray.push(new Date(tempDate.setDate(tempDate.getDate() + 1)));
    }
  }
  return datesArray;
}

const handleNextClick = () => {
    /* adding a week to the date stripe dats array */
    const lastDate = datesData[datesData.length - 1];
    const nextDate = new Date(lastDate.setDate(lastDate.getDate() + 1));
    setDatesData(datesData.concat(getDatesArray(new Date(nextDate), datesToDisplay)));
}

当我观察到这个 const nextDate = new Date(lastDate.setDate(lastDate.getDate() + 1)); 行导致问题。任何想法如何做到这一点?

标签: reactjstypescriptdate

解决方案


你对问题线是正确的。const nextDate = new Date(lastDate.setDate(lastDate.getDate() + 1));表示“将 1 加到lastDate,然后使用nextDate与新更新的 相同的值lastDate。” 你想要这个:

const nextDate = new Date(lastDate.getTime());
nextDate.setDate(nextDate.getDate() + 1);

这意味着“nextDate与 具有相同的值lastDate,然后将 1 添加到nextDate。”


推荐阅读