gpt4 book ai didi

javascript - 在 array.map 中添加一个值是否被认为是变异的?

转载 作者:行者123 更新时间:2023-11-29 16:06:54 25 4
gpt4 key购买 nike

我知道 redux 对状态管理很严格,但是从对象数组中添加一个值在 redux 中被认为是不行的吗?示例:

// Consider this array of objects on action
action.arr = [ { test: 'me', hail: 'hydra'}, { test: 'you', ring: 'of fire'} ]
// reducer.js
fn = (state = defaultState, action) => {
...
case action.LORD_COMMANDER:
return action.arr.map(v => {
v.john = 'snow'
return v
})
...
}

这在我的 reducer 上是否完全安全,还是我应该使用 Object.assign()

最佳答案

我认为最好使用 Object.assign。让我们考虑两个例子

const arr  = [ { test: 'me', hail: 'hydra'}, { test: 'you', ring: 'of fire'} ];
const arr1 = arr.map(v => {
v.john = 'snow'
return v;
});

console.log(arr, arr1);

如您所见,两个数组中的每个 Object 都有属性 john,因为我们更改了 Objects,它们具有相同的引用,这对以前的引用不安全Array.,在下面的例子中你可以看到只有在第二个 Array 对象有属性 john 这是因为我们复制了 Object

const arr  = [ { test: 'me', hail: 'hydra'}, { test: 'you', ring: 'of fire'} ];
const arr1 = arr.map(v => {
return Object.assign({}, v, { john: 'show' })
});

console.log(arr, arr1);

关于javascript - 在 array.map 中添加一个值是否被认为是变异的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39240694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com