reactjs - 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)); 行导致问题。任何想法如何做到这一点?
解决方案
你对问题线是正确的。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
。”
推荐阅读
- laravel - vuejs 配置多数据源
- python - Python:pathos 和 selenium 的酸洗问题
- javascript - 使用 Javascript Reduce 添加一个属性并乘以另一个属性
- php - Halite/Doctrine vs MySQL AES_ENCRYPT:安全/性能
- excel - Excel VBA 查找
- c# - C# - 从程序集调用方法到其他导致 DllNotFoundException
- c# - 如何在 XAML 中引用另一个程序集中基于第三个程序集中枚举的依赖属性
- java - 程序类型已经存在:android.support.v7.util.AsyncListUtil$1
- autowired - Symfony 4 自动装配无法调试
- android - Android - 下载 SVG 图像并在 ImageView 中显示