获得"TypeError: Cannot read property 'map' of undefined"



我想通过使用foreach循环来更改此状态对象的值。现在,当我使用映射函数时,它工作得很好。但是当我使用foreach循环时得到了错误。状态对象是

state = {
counters: [
{ id: 1, value: 4 },
{ id: 2, value: 0 },
{ id: 3, value: 0 },
{ id: 4, value: 0 },
],
};
handleReset = () => {
var counters = this.state.counters.forEach((c) => {
c.value = 0;
});
this.setState({ counters });
};

方法forEach变异原始数组,而map则从原始数组生成新的变异数组。在你的情况下,地图是正确的方法。不能使用forEach直接更改状态。