[英]How to update state of 2D array with N objects inside in React?
Before I jump on subject, I want to mention that I've already referred to questions like these, but could not figure the solution on my own.在我进入主题之前,我想提一下,我已经提到了这些问题,但我自己无法找到解决方案。
Updating React state as a 2d array? 将 React 状态更新为二维数组?
Let's assume this is my state object让我们假设这是我的状态对象
state = {
graphData: [
[{x: 0, y: 0}],
],
};
As time increases, graphData will get bigger and might look something like this随着时间的增加,graphData 会变得更大,可能看起来像这样
graphData: [
[{x: 0, y: 0}, {x: 1, y:1}, {x:2, y:2}],
],
At the moment, I handle that in this manner:目前,我以这种方式处理:
nextGraphData = this.state.graphData[0][graphDataLength] = {x: lastXAxisValue + 1, y: value};
this.setState({
graphData: {
...this.state.graphData,
nextGraphData
}
});
Obviously, I get an error saying I should not mutate state directly.显然,我收到一条错误消息,说我不应该直接改变 state。 So, how to achieve the same without direct mutation.那么,如何在不直接突变的情况下实现相同的目标。 I tried to play around a bit, but could not figure it out.我试着玩了一下,但无法弄清楚。
Try this尝试这个
state = {
graphData: [
[{x: 0, y: 0}],
],
};
use like this像这样使用
this.setState({
...this.state,
graphData: [...this.state.graphData, {x:1,y:1}]
})
The error appears because of this line由于这一行出现错误
nextGraphData = this.state.graphData[0][graphDataLength] = {x: lastXAxisValue + 1, y: value};
as you are trying to assign value directly to the state.graphData
当您尝试直接为state.graphData
what you have to do is to change it like this:你要做的就是像这样改变它:
let nextGraphData = {...this.state.graphData,{x: lastXAxisValue + 1, y: value}};让 nextGraphData = {...this.state.graphData,{x: lastXAxisValue + 1, y: value}};
this.setState({
graphData: {
...nextGraphData
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.