在formatHours()
下面的函数中,我尝试分配newHours
给selectedLocation.data.hours
(一个对象)
我正在使用传播运算符来克隆对象,以便函数完成时selectedLocation.data.hours
保持不变,但事实并非如此。该函数运行后,selectedLocationd.data.hours
现在等于newHours
。
formatHours():
const formatHours = () => {
// ERROR: trying to clone selectedLocation.data.hours, but not working
const newHours = { ...selectedLocation.data.hours };
// loop through all hours and convert them to javascript date with .toDate()
for (const hour in newHours) {
newHours[hour][0] = newHours[hour][0].toDate();
newHours[hour][1] = newHours[hour][1].toDate();
}
// set hours state with updated hours
setHours(newHours);
};
这selectedLocation.data.hours
看起来像是在传递之前formatHours()
:
(Firebase Firestore时间戳记数组的对象)
这是selectedLocation.data.hours
经过它之后的样子formatHours()
:
(JavaScript Date对象数组的对象)
注意: selectedLocation.data.hours
该功能前后应保持不变,但不是。我肯定错过了什么。
无需更改newHours[hour]
数组(该数组会使当前处于状态/属性的对象发生变化),而无需在该位置使用所需的属性创建一个全新的数组:
// Shallow clone newHours
const newHours = { ...selectedLocation.data.hours };
// Reassign each property; it'll affect the clone, not the original
for (const [hour, arr] of Object.entries(newHours)) {
newHours[hour] = [
arr[0].toDate(),
arr[1].toDate(),
arr[2]
];
}
另一种方法是Object.fromEntries
:
const newHours = Object.fromEntries(
Object.entries(selectedLocation.data.hours).map(([hour, arr]) => (
[ // return an entry array
hour, // key in new object
[ // value in new object
arr[0].toDate(),
arr[1].toDate(),
arr[2]
]
]
))
);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句