[英]Create a immutable copy of a property
我遇到一種情況,我想制作一個屬性的不可更改的副本以將狀態恢復到原始狀態。
我有一個陣列group
的對象。
在每個group
我都有一系列items
。
當我進行復印時,一切都很好。
我首先這樣做。
componentDidMount(){
// originalGroups = Object.assign([], this.props.modalitygroups);
originalGroups = JSON.parse(JSON.stringify(this.props.modalitygroups));
},
我已經嘗試了以上兩個語句,但是已經閱讀到當前的活動語句可以真正復制對象。 針說它確實復制正確。
然后,我將具有此搜索功能來搜索組和項目中的項目。
_searchFilter:function(search_term){
this.setState({modalitygroups:originalGroups});
let tempGroups = Object.assign([], this.state.modalitygroups);
if(search_term !== ''){
for (let x = (tempGroups.length) - 1; x >= 0; x--)
{
console.log("originalGroups",x,originalGroups);
for (let i = (tempGroups[x].items.length) - 1; i >= 0; i--)
{
if(!tempGroups[x].items[i].description.toLowerCase().includes(search_term.toLowerCase())){
tempGroups[x].items.splice(i,1);
}
}
if(tempGroups[x].items.length === 0){
tempGroups.splice(x, 1);
}
}
this.setState({modalitygroups:tempGroups});
}
},
因此,我首先恢復原始狀態以啟用對所有內容的搜索。 搜索功能循環通過每個組,並且在每個組循環中,我循環遍歷每個項目,刪除不包含搜索短語的項目。
遍歷每個項目之后,如果組中沒有剩余項目,我也將從group
數組中刪除該組。
第一次使用時效果很好。
但是,當我開始搜索新項目時,我發現originalGroups
也已更改。 先前刪除的items
也已從unchangable
副本中刪除,我不知道為什么。 它在哪里以及為什么更改我的安全副本?
希望這是有道理的。
const state = { property1: 42 }; const originalGroups = Object.freeze(state); originalGroups.property1 = 33; // Throws an error in strict mode console.log(originalGroups.property1); // expected output: 42
從本質上講,畢竟ReactJS
仍然是javascript
,因此您可以應用Object.freeze來保存狀態副本
那么模態組包含原始組嗎? 這是很難跟隨......而不是“保存”原來所屬的組,我會離開this.props.modalitygroups獨自復制到filteredGroups
狀態。 您可以從永不改變的道具中重新加載。
在過濾器函數中, let tempGroups = Object.assign([], this.state.modalitygroups);
那應該是您使用json創建深層副本的地方。 那就是用舊數組中的相同組引用填充新數組,因此您要在原始數組中修改相同的組實例。
_searchFilter:function(search_term){
// deep copy
let tempGroups = JSON.parse(JSON.stringify(this.props.modalitygroups));
if(search_term !== ''){
for (let x = (tempGroups.length) - 1; x >= 0; x--)
{
console.log("originalGroups",x,originalGroups);
for (let i = (tempGroups[x].items.length) - 1; i >= 0; i--)
{
if(!tempGroups[x].items[i].description.toLowerCase().includes(search_term.toLowerCase())){
tempGroups[x].items.splice(i,1);
}
}
if(tempGroups[x].items.length === 0){
tempGroups.splice(x, 1);
}
}
this.setState({modalitygroups:tempGroups});
}
},
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.