React JS中嵌套动态对象数组中的SetState和push对象
SetState and push object in array in nested dynamic array of objects in React JS
我有两个具有相同对象属性的数组,我只想更新一个数组中的特定对象数据而不影响第二个对象数组。
我已经尝试 JSON 解析,但它没有用,因为我在数据上使用拖放,所以我想更新特定对象传递索引。
this.state = {
listItem: [
// This data will be static
{ data: `Text`, content: 'Insert you text here...' },
{
data: `Column`,
content: 'Column',
columns: [
{
column: []
},
{
column: []
}
]
}
],
layout:[
// The data below might be more than 3-4 times repetitive
{
data: `Column`,
content: 'Column',
columns: [
{
column: []
},
{
column: []
}
]
}
]
}
// Set State function I tried recently
onColumnDrop(e, layoutIndex, colIndex) {
if (e.removedIndex !== null || e.addedIndex !== null) {
var stateCopy = Object.assign({}, this.state.layout);
stateCopy[layoutIndex].columns[colIndex].column = e.payload;
this.setState({ stateCopy });
}
}
所以,基本上功能是当我从 listItem 拖动对象并放入布局列数组时,所以我想在列 [0] 或列 [1] 数组中设置拖动对象的状态,所以发生的事情是当我继续将 listItem[0] 推入 column[0] 或 column[1] 数组,然后同时更新 listItem 列,不知道为什么!但我非常困惑。
这听起来很像您在代码中多次引用同一个对象,这很可能是 var stateCopy = Object.assign({}, this.state.layout);
的结果。此行仅浅层复制状态,这意味着不会复制状态中较深的对象和数组,而只会复制对对象的引用。因此,当您执行 stateCopy[layoutIndex].columns[colIndex].colum = e.payload;
.
时,您基本上最终会改变原始状态
为了避免这个问题,你要么必须JSON.parse(JSON.stringify(state))
,这似乎是不可能的,要么你必须自己实现深度复制,在其中复制所有级别的状态。
我有两个具有相同对象属性的数组,我只想更新一个数组中的特定对象数据而不影响第二个对象数组。
我已经尝试 JSON 解析,但它没有用,因为我在数据上使用拖放,所以我想更新特定对象传递索引。
this.state = {
listItem: [
// This data will be static
{ data: `Text`, content: 'Insert you text here...' },
{
data: `Column`,
content: 'Column',
columns: [
{
column: []
},
{
column: []
}
]
}
],
layout:[
// The data below might be more than 3-4 times repetitive
{
data: `Column`,
content: 'Column',
columns: [
{
column: []
},
{
column: []
}
]
}
]
}
// Set State function I tried recently
onColumnDrop(e, layoutIndex, colIndex) {
if (e.removedIndex !== null || e.addedIndex !== null) {
var stateCopy = Object.assign({}, this.state.layout);
stateCopy[layoutIndex].columns[colIndex].column = e.payload;
this.setState({ stateCopy });
}
}
所以,基本上功能是当我从 listItem 拖动对象并放入布局列数组时,所以我想在列 [0] 或列 [1] 数组中设置拖动对象的状态,所以发生的事情是当我继续将 listItem[0] 推入 column[0] 或 column[1] 数组,然后同时更新 listItem 列,不知道为什么!但我非常困惑。
这听起来很像您在代码中多次引用同一个对象,这很可能是 var stateCopy = Object.assign({}, this.state.layout);
的结果。此行仅浅层复制状态,这意味着不会复制状态中较深的对象和数组,而只会复制对对象的引用。因此,当您执行 stateCopy[layoutIndex].columns[colIndex].colum = e.payload;
.
为了避免这个问题,你要么必须JSON.parse(JSON.stringify(state))
,这似乎是不可能的,要么你必须自己实现深度复制,在其中复制所有级别的状态。