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