修改嵌套的redux状态而不会变异(modifiying nested redux state without mutating)

编程入门 行业动态 更新时间:2024-10-25 01:24:11
修改嵌套的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.

更多推荐

本文发布于:2023-08-02 23:46:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1382470.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:嵌套   状态   redux   modifiying   state

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!