【发布时间】:2018-10-14 23:31:47
【问题描述】:
我正在开发一个餐桌规划器应用程序,可以将客人分配到餐桌。 我在名为 tabledata 的状态下创建了一个对象数组,其中将包含如下对象:
this.state = {
tabledata: [
{
name: "Top Table",
guests: ["guest1", "guest2", "guest3"]
},
{
name: "Table One",
guests: ["guest3", "guest4", "guest5"]
}
]
}
然后我正在创建一个拖放界面,客人可以在其中在桌子之间移动。我试图像这样更新状态:
updateTableList (tablename, guest) {
const selectedTableObj = this.state.tabledata.filter((tableObj) => tableObj.name === tablename);
const otherTableObjs = this.state.tabledata.filter((tableObj) => tableObj.name !== tablename);
selectedTableObj[0].guests.push(guest);
const updatedObjectArray = [...otherTableObjs, selectedTableObj];
this.setState({
tabledata: [...otherTableObjs, ...selectedTableObj]
});
}
这可行,但是因为我从状态中删除 selectedTableObj 然后将其添加到数组的末尾,所以我在屏幕上得到了一些时髦的结果。更新后的表格始终位于页面底部(如您所料)。
如何更新对象而不改变其在数组中的位置?
【问题讨论】:
标签: javascript arrays reactjs object setstate