简体   繁体   English

如何在 React 中使用 N 个对象更新 2D 数组的状态?

[英]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.

相关问题 如何更新对象的反应状态数组 - How to update react state array of objects 如何在 javascript 的列内创建一个包含对象数组的二维数组? - How to create a 2d array with array of objects inside columns in javascript? 使用 2 个不同的字符串更新 2D state 数组 - Update 2D state array with 2 different strings 在 React State 中更新对象数组 - Update an Array of Objects in React State React-更新2D数组的状态,并使用.map函数和new Array.fill将其填充为随机数 - React - Update state of 2D array and fill it with random numbers using .map function and new Array.fill 如何在反应中使用 useState 更新或分配二维数组 - how to update or assign 2d array using useState in react 如何对对象数组进行分组并更新 React 中的状态 - How to group array of objects and update the state in react React 如何在反应 state 中更新嵌套对象数组中的数组? - How to update the array in nested array of objects in react state? 在 React 中使用 useState 更新二维数组矩阵 - Update a 2D array matrix with useState in React React-生命游戏-根据用户单击的元素来更新2D数组中特定元素的状态 - React - Game of Life - Update state of specific elements in 2D array depending on which elements are clicked by user
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM