反应状态中的递增和递减数组计数器



我有一些麻烦试图找出为什么我不能正确地在一个数组中增加/减少四个计数器,这是在应用程序状态。这个状态下的数组是这样的:

...
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数据,并将传入的数据保存在"左"、"右"、"上"。和";down"你可以在这个州看到的变化。我选择哪个计数器应该递增/递减(我称之为'bank'),读取' left ';和";right"JSON数据,并使用"up"one_answers";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;
}
}
}

我没有在状态中保存bank值,因为它不应该被渲染。递增/递减函数出现了问题:

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 });
}
}
}

我看到React引擎在第7行和第14行抱怨,说我不应该直接改变状态,但我在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
我尝试了这么多的解决方案,我要疯了,任何帮助我将感激…您可以在这里找到完整的代码,但请记住,它在渲染方法中仍在进行中(第一个银行是唯一可用的,仍在测试各种解决方案)。我希望我给了你所有的信息来帮助我修复错误。

我发现你的代码有几个问题。

  1. bank的值为array。你试图用this.setState({ bank: bankValue })
  2. 将其更改为整数
  3. State应该是不可变的,如果你想改变这个值,你需要创建一个新的数组并设置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

最后,我设法解决了这个问题。我使用扩展操作符来处理这个问题,并避免在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方法。谢谢你的建议!

最新更新