RCo*_*hen 2 javascript reactjs
我有一个需要迭代的 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
})
}
Run Code Online (Sandbox Code Playgroud)
谢谢!:)
您可以Map
使用for of
以下方法迭代对象:
for (const [key, value] of myMap) {
console.log(key, value);
}
Run Code Online (Sandbox Code Playgroud)
这与迭代条目相同:
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}
Run Code Online (Sandbox Code Playgroud)
正如@Nina Scholz 所说,您可以forEach
在Map
原型(doc MDN)上使用:
myMap.forEach((value, key, map) => {
console.log(key, value);
}
Run Code Online (Sandbox Code Playgroud)
Map
s 提供了三种方法来获取其内容的迭代器:
正如尼娜所指出的,Map
s 也提供forEach
,它循环遍历它们的内容,为回调提供值、键和映射作为参数。
使用适合您的用例的一种。例如,如果您要替换Object.keys
,请使用keys
。同样,如果您想要地图中的条目(我注意到您曾经使用Object.entries
过),请使用entries
或 默认迭代器。
请注意,在您的代码中的一些地方,您似乎试图使用[]
. 这不适用于地图,您需要使用get
.
这是一个使用默认迭代器的简单示例(这也是您从中获得的entries
):
const map = new Map();
map.set(1, "one"); // Could also include these when calling
map.set(2, "two"); // the constructor but I wanted to
map.set(3, "three"); // avoid any confusion
for (const [key, value] of map) { // Using the default iterator (could be `map.entries()` instead)
console.log(`The value for key ${key} is ${value}`);
}
Run Code Online (Sandbox Code Playgroud)
还要注意的是你打破阵营的规则,一个通过设置基于现有状态的新状态,但不使用的回调版本setState
。如果在设置新状态时需要使用现有状态,则必须使用回调版本:
this.setState(prevState => {
// ...use `prevState` values (*not* `this.state`!) to create an object with
// the updates, then return the object...
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
6085 次 |
最近记录: |