简体   繁体   English

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

[英]Is adding a value inside an array.map considered mutating?

I know redux is strict with state management, but is adding a value from an array of objects considered a no no in redux? 我知道redux在状态管理上很严格,但是是否在redux中从一个对象数组中添加了一个值呢? Example: 例:

 // 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 }) ... } 

Is this completely safe on my reducer or should I use Object.assign() ? 这对我的reducer来说是完全安全的,还是应该使用Object.assign()

I think better use Object.assign . 我认为最好使用Object.assign Let's consider two examples 我们来看两个例子

 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); 

As you can see each Object in two arrays have property john because we change Objects which have same reference that is not safe for previous Array ., in example below you can see that only in second Array Objects have property john it is because we make copy of Object 如您所见,两个数组中的每个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); 

in this case you are making your state to be the array and since the array in the action is always going to be different then yes you are mutating the state. 在这种情况下,您要使状态成为数组,并且由于动作中的数组总是不同的,所以是的,您是在改变状态。 as long as the objects are not references the state will be completely mutated a sample of a dirty state is. 只要对象没有被引用,状态将被完全变异为脏状态的样本。 var objA = {}; var objB = {}; action.array = [objA, objB];

in this case when you do the map your reference to the array would be new but the reference to the objects would be the same. 在这种情况下,当您执行映射时,对数组的引用将是新的,但对对象的引用将是相同的。 here it would be advised to use Object.assign or (...) operator inside of your map function. 建议您在地图函数中使用Object.assign或(...)运算符。 or better yet i would recommend looking into immutablejs to handle immutable data 或更好,但我建议研究inmutablejs以处理不可变数据

https://facebook.github.io/immutable-js/ https://facebook.github.io/immutable-js/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM