修改嵌套的redux状态而不会变异(modifiying nested redux state without mutating)
我是否用这个函数突变了redux状态?
function addDefinition(object, payload) { var newObject = Object.assign({}, object); if(!newObject[payload.guid]){ newObject[payload.guid] = []; } newObject[payload.guid].push(payload); return newObject; }我想创建结构来保存与应用程序不同部分有关的数据。
Am i Mutating redux state with this function ?
function addDefinition(object, payload) { var newObject = Object.assign({}, object); if(!newObject[payload.guid]){ newObject[payload.guid] = []; } newObject[payload.guid].push(payload); return newObject; }I want to create structure to hold data related to different part of application.
最满意答案
是的,那个.push()语句在稍后的调用中是变异的。 在第一次调用中,该数组是新创建的,因此它不符合突变。 在稍后的调用中,您创建了一个新对象,但复制了现有的数组引用,所以.push()改变现有的数组。
Yes, that .push() statement is mutating in the later calls. In the first call, the array is newly created, so it doesn't qualify as a mutation. In a later call, you've created a new object but copied the existing array reference, so .push() mutates the existing array.
更多推荐
发布评论