且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检索商店状态的旧值和新值

更新时间:2023-12-06 15:10:22

假设当您在 Javascript 中创建数组/对象时,

let say when you create an array/object in Javascript,

 var arr = [1,2,3];

这会在浏览器的内存中创建一个数组.但是 arr 变量包含的不是整个数组值,它包含对浏览器内存中数组的引用.您可以将其视为 arr 包含一个地址,该地址可以将您指向浏览器内存中的真实数组值.

This creates an array in the browser's memory. But what arr variable contains is not the entire array value, it contains the reference to the array in browser memory. You could think of it as arr contains an address that can point you to the real array value in browser's memory.

如果你这样做

var arr = [1,2,3];
var arr2 = arr;
arr2[0] = 4;
console.log(arr); // you would get [4,2,3];

编辑arr2 也改变了arr.因为它们都指向浏览器内存中的同一个数组.

editing arr2 changed arr too. Because they both point to the same array in browser memory.

这就是旧值将与新值相同,因为它们引用相同的对象/数组"的意思.

That's what "the old value will be the same as the new value because they reference the same Object/Array" means.

同样的原则也适用于对象.在 Javascript 中,数组只是一种特殊类型的对象.

The same principle applies to object as well. In Javascript, an array is just a special type of object.

要在观察者中检索数组的不同版本,您必须在每次对其进行变异时克隆它以将其设置为新数组.

to retrieve the different versions of the array in the watcher, you must clone it to set it as a new array everytime you mutate it.

例如,

state.orderBookSell = [...state.orderBookSell];

BUT..... [...array] 是浅克隆,不是深克隆.这是一个问题.你有一个对象数组.请记住,对象也具有相同的规则.它们是通过引用传递的.所以你必须做一个深度克隆,这样所有的对象也都被克隆了.

BUT..... [...array] is shallow cloning, not deep cloning. And that's a problem. You have an array of objects. Remember that object also have the same rules. They are passed by reference. So you gotta do a deep clone, so that all the objects is cloned as well.

使用 lodash cloneDeep 方法进行深度克隆

using lodash cloneDeep method for deep cloning

state.orderBookSell = _.cloneDeep(state.orderBookSell);