【发布时间】:2017-04-19 00:59:58
【问题描述】:
我有一组处于 React 状态的对象: this.state.expandableRowSwitches 是一个对象数组:
{显示:假,选择:假,重影:假}
当我尝试制作数组的副本来操作它(深或浅)时,如果我在复制行之后使用操作数组的特定索引的行,我不会得到精确的副本。如果我注释掉该行,则副本在执行时会恢复到完美状态。唯一不这样做的复制数组的单一形式是 JSON.parse(JSON.stringify) 但我不想依赖它作为一种方法。我尝试了其他所有方法,包括 lodash 的 deepClone,甚至是一个普通的 for 循环。同样,当我使用 JSON.parse 方法时,我的程序按预期执行。任何帮助将不胜感激。
onTableRowDoubleClick(index) {
console.log('onTableRowDoubleClick');
let arrayCopy = [];
arrayCopy = _.cloneDeep(this.state.expandableRowSwitches);
//let arrayCopy = _.clone(this.state.expandableRowSwitches);
//let arrayCopy = this.state.expandableRowSwitches.splice(0);
//let arrayCopy = [...this.state.expandableRowSwitches];
//let arrayCopy = this.state.expandableRowSwitches.slice(0);
arrayCopy[index].display = !arrayCopy[index].display;
return arrayCopy;
}`
【问题讨论】:
-
我不确定你的问题,但你试过Array.from()吗?
-
我刚刚尝试过,arrayCopy = Array.from(this.state.expandableRowSwitches) 给了我同样的问题。所有开关都转换为真(它们开始为假)。当只有一行应该扩展时,这具有我所有行扩展的效果(通过仅针对该单个索引将显示开关设置为 true)。当我使用 JSON.parse(JSON.stringify... 作为复制方法时,一切都按预期工作。虽然我不想依赖该复制方法
-
@JaredBoice 见stackoverflow.com/help/someone-answers
标签: javascript arrays reactjs deep-copy