[英]Unable manage objects in array independently
I'm working on a text editor using React and I want to keep track of the changes in an array.我正在使用 React 开发文本编辑器,我想跟踪数组中的更改。 Whenever I make changes an object is added to the array (as it should) but all the other objects change as well and become the same as the new one.
每当我进行更改时,都会将一个对象添加到数组中(应该如此),但所有其他对象也会更改并与新对象相同。 I'm aware of how Javascript doesn't store objects in independent variables if not reassigned so I used the spread operator to create a new array and then add a new object using
Object.assign()
but it's still not working and I can't figure out what I'm doing wrong.我知道如果没有重新分配,Javascript 不会将对象存储在自变量中,所以我使用扩展运算符创建一个新数组,然后使用
Object.assign()
添加一个新对象,但它仍然无法正常工作,我可以'不知道我做错了什么。
getNewChangesHistory(update, oldChangesHistory){ var newChangesHistory = [...oldChangesHistory, Object.assign({}, update)]; if(newChangesHistory.length > 25){ delete(newChangesHistory[26]); } return newChangesHistory; } updateDocumentContent(content){ var newDocument = {...this.state.document}; newDocument.content = content; this.setState(prevState => {return { document: newDocument, changesHistory: this.getNewChangesHistory(content, prevState.changesHistory), hasChanges: true }}) } updateTextbox(editedProperties, key){ const newDocumentContent = {...this.state.document.content}; newDocumentContent.textboxes[key] = { //Textboxes are stored as objects of an array ...editedProperties, id: key } this.updateDocumentContent(newDocumentContent) } render(){ return( <TextBox onEdit={(editedProperties) => {this.updateTextbox(editedProperties, 0)}} /> ) }
The problem is in updateTextbox
.问题出在
updateTextbox
中。 With {...this.state.document.content}
it only creates a shallow copy.使用
{...this.state.document.content}
它只会创建一个浅拷贝。 In this copy the textboxes
property will still reference the same object.在此副本中,
textboxes
属性仍将引用同一个对象。 And you mutate that object by the assignment to its [key]
property.然后你通过赋值给它的
[key]
属性来改变那个对象。 So that mutation will be seen in all objects that have that same textboxes
object reference.因此,将在具有相同
textboxes
对象引用的所有对象中看到该突变。
One way to get rid of this, is to treat textboxes
as immutable, and do this:摆脱这种情况的一种方法是将
textboxes
视为不可变的,并执行以下操作:
updateTextbox(editedProperties, key){
const {content} = this.state.document;
const newDocumentContent = {
...content,
// create a new textboxes array
textboxes: Object.assign([], content.textboxes, {
[key]: {
...editedProperties,
id: key
}
})
};
this.updateDocumentContent(newDocumentContent);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.