我有一个需要迭代的 Map() 对象,因此我可以获得星期几和选定的小时。下面的代码不起作用,因为Object.keys(newFieldReservationPrice).forEach
它试图循环一个 Map() 对象,这似乎没有意义。那么,有没有更好的解决方案呢?
这是下面的代码:
handlePriceInput = (e, hour, day) => {
let value = e.target.value
const newFieldReservationPrice = this.state.newFieldReservationPrice
console.log('newFieldReservationPrice', newFieldReservationPrice) // A Map();
let map;
if (!newFieldReservationPrice instanceof Map) {
console.log('!== Map')
console.log('newFieldReservationPrice is a Map()? inside if ()', newFieldReservationPrice)
if (newFieldReservationPrice[day] && newFieldReservationPrice[day][hour]) {
newFieldReservationPrice[day][hour] = Number(value)
}
} else {
map = new Map();
console.log('map object', Object.keys(newFieldReservationPrice)) // logs map object []
Object.keys(newFieldReservationPrice).forEach(key => {
console.log('key', key)
map.set(key, new Map(Object.entries(newFieldReservationPrice[key])));
}); // This doesn't work
console.log('Am I a Map()? map', map)
const aux = map.get(day)
console.log('aux day', aux) // A Map()
aux.set(hour, Number(value)) // Comes as undefined || Cannot read property 'set' of undefined
console.log('aux set', aux) // A Map()
map.set(day, aux);
console.log('what do I have?', map)
}
const isReservationPrice = !newFieldReservationPrice instanceof Map ? newFieldReservationPrice : map
console.log('isReservationPrice', isReservationPrice)
this.setState({
newFieldReservationPrice: isReservationPrice
})
}
谢谢!:)
Map
s 提供了三种方法来获取其内容的迭代器:
正如尼娜所指出的,Map
s 也提供forEach
,它循环遍历它们的内容,为回调提供值、键和映射作为参数。
使用适合您的用例的一种。例如,如果您要替换Object.keys
,请使用keys
。同样,如果您想要地图中的条目(我注意到您曾经使用Object.entries
过),请使用entries
.
请注意,在您的代码中的一些地方,您似乎试图使用[]
. 这不适用于地图,您需要使用get
.
还要注意的是你打破阵营的规则,一个通过设置基于现有状态的新状态,但不使用的回调版本setState
。如果在设置新状态时需要使用现有状态,则必须使用回调版本:
this.setState(prevState => {
// ...use `prevState` values (*not* `this.state`!) to create an object with
// the updates, then return the object...
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句