Javascript 如何在 React 中深度克隆对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48710797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I deep clone an object in React?
提问by SpaceDogCS
let oldMessages = Object.assign({}, this.state.messages);
// this.state.messages[0].id = 718
console.log(oldMessages[0].id);
// Prints 718
oldMessages[0].id = 123;
console.log(this.state.messages[0].id);
// Prints 123
How can I prevent oldMessagesto be a reference, I want to change the value of oldMessageswithout changing the value of state.messages
我怎样才能防止oldMessages被引用,我想改变的值oldMessages而不改变的值state.messages
回答by AryanJ-NYC
You need to make a deep copy. Lodash's cloneDeepmakes this easy:
你需要做一个深拷贝。Lodash 的 cloneDeep使这变得简单:
import cloneDeep from 'lodash/cloneDeep';
const oldMessages = cloneDeep(this.state.messages);
oldMessages[0].id = 123;
Good luck!
祝你好运!
回答by Anjali
Try Using
尝试使用
let tempVar = JSON.parse(JSON.stringify(this.state.statename))
回答by Hozefa
One of the best ways to deep clone objects is using the spreadoperator. It does deep cloning without us having to write any extra code.
深度克隆对象的最佳方法之一是使用spread运算符。它可以进行深度克隆,而无需我们编写任何额外的代码。
For example...
例如...
const obj1 = {foo: {baz: 'bar'}}
const obj2 = {test: 'temp}
const obj3 = {...obj1, ...obj2}
// obj3 = {foo: {baz: 'bar'}, test: 'temp}

