我在试图找出为什么不能正确地增加/减少数组中的四个计数器时遇到了一些困难,这个数组处于app状态。状态中的数组如下:
...
constructor(props) {
super(props);
this.state = {
right: 0,
left: 0,
up: 0,
down: 0,
...more variables...
bank: [0, 0, 0, 0] // <- array with 4 counters set to zero
};
}
...
应用程序从Node.js服务器获取JSON数据,并将传入的数据保存在状态中可以看到的“左”、“右”、“上”和“下”的vars中。我选择哪个计数器应该递增/递减(我称之为'bank'),读取“左”和“右”的JSON数据,并使用"up“和"down”来增加或减少。这些信号工作正常,但问题在于我认为的逻辑。这是处理银行选择(计数器)的功能:
bankSelection() {
if (parsedJsonData.right) {
currentBank += 1;
if (currentBank > maxBank) { // restart from zero
currentBank = 0;
}
} else if (parsedJsonData.left) {
currentBank -= 1;
if (currentBank < 0) { // restart from 3
currentBank = 3;
}
}
}
我不把银行价值存在州里,因为它不应该被渲染。问题在于增量/递减函数:
updateCounters() {
if (parsedJsonData.up) {
if (this.state.bank[currentBank] < 9) {
let bankValue = this.state.bank[currentBank] + 1;
this.setState({ bank: bankValue });
} else {
this.setState({ bank: this.state.bank[currentBank] = 0 });
}
} else if (parsedJsonData.down) {
if (this.state.bank[currentBank] > 0) {
let bankValue = this.state.bank[currentBank] - 1;
this.setState({ bank: bankValue });
} else {
this.setState({ bank: this.state.bank[currentBank] = 9 });
}
}
}
我在第7行和第14行看到了function引擎的抱怨,说我不应该直接改变状态,但是我在一个setState函数中!除此之外,当我发送如下格式的JSON时:
{
"left": 0,
"right": 0,
"up": 1,
"down": 0
}第一次正确更新第一银行中的计数器并显示值1时,第二次在浏览器的控制台中得到此错误:
Uncaught (in promise) TypeError: Cannot create property '0' on number '1'
at App.updateCounters (App.js:145:1)
at App.js:112:1我尝试了这么多的解决方案,我要疯了,任何帮助我都会感激.您可以找到这里的完整代码,但请记住,在呈现方法中它仍在进行中(第一个银行是唯一可用的,仍在测试各种解决方案)。我希望我给你所有的信息,以帮助我纠正错误。
发布于 2022-06-15 08:05:14
我看到你的代码有一些问题。
bank的值是数组。您试图用this.setState({ bank: bankValue })将其更改为整数。bank状态。就像这样:this.setState({bank: Object.values({...this.state.bank, 1: 100}); // where 1 is the idx where you want to update the value, and 100 is the new value发布于 2022-06-17 08:41:32
最后,我设法解决了这个问题。我使用spread操作符来实现这一点,并避免了setState方法中的直接分配。
updateCounters() {
if (parsedJsonData.up) {
if (this.state.bank[currentBank] < 9) {
// let bankValue = this.state.bank[currentBank] + 1;
var newArrayUp = [...this.state.bank];
newArrayUp[currentBank] += 1;
console.log("array clonato dopo aggiornamento " + [...newArrayUp]);
this.setState({ bank: [...newArrayUp] }, () => {
this.forceUpdate();
});
} else {
var zeroArray = [...this.state.bank];
zeroArray[currentBank] = 0;
console.log(zeroArray[currentBank]);
this.setState({ bank: [...zeroArray] });
this.forceUpdate();
}
} else if (parsedJsonData.down) {
if (this.state.bank[currentBank] > 0) {
var newArrayDown = [...this.state.bank];
newArrayDown[currentBank] -= 1;
console.log("array clonato dopo aggiornamento " + [...newArrayDown]);
this.setState({ bank: [...newArrayDown] }, () => this.forceUpdate());
} else {
var nineArray = [...this.state.bank];
nineArray[currentBank] = 9;
console.log(nineArray[currentBank]);
this.setState({ bank: [...nineArray] }, () => this.forceUpdate());
}
}
}
现在,我创建一个原始数组的副本,对其进行处理,然后将其传递给setState方法。谢谢你的建议!
https://stackoverflow.com/questions/72627673
复制相似问题