在array.map中添加一个值是否考虑变异?

mat*_*yow 2 javascript reducers reactjs redux

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

// 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
    })
  ...
}
Run Code Online (Sandbox Code Playgroud)

这对我的减速机是否完全安全或我应该使用Object.assign()

Ale*_* T. 5

我认为更好用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);
Run Code Online (Sandbox Code Playgroud)

正如你所看到的Object,两个数组中的每一个都具有属性,john因为我们更改了具有相同引用的对象,这对于前面的代码是不安全的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);
Run Code Online (Sandbox Code Playgroud)