gpt4 book ai didi

javascript - 如何更新不可变列表中的特定值?

转载 作者:行者123 更新时间:2023-11-28 18:54:21 25 4
gpt4 key购买 nike

我正在开发 redux架构,尝试使用Immutable.js .

这是我的谜团......鉴于这种状态:

var state = Immutable.fromJS([
{"id":0, "url":"http://someUrl", "thumb_url":"http://someUrl", "other_url":"http://someUrl"},
{"id":3, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":1, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":5, "url":"http://someUrl", "thumb_url":"http://someUrl", "yet_another_url":"http://someUrl"}
])

...我想更新url。我尝试更新第三个 indexurl,如下所示:

var index = 2;
var new_item = { id: 1, url: 'my_new_url' };

var state = state.setIn([index], new_item);

我的问题是,我只需要更新 url (或其他属性,如 thumb_url),保持所有未更改的属性不变。我有一个 new_item ,我想将其中的相关更新部分插入到给定索引中。如何在不递归旧项目的每个单独属性且不丢失现有属性的情况下做到这一点?

当我说“更新”时,我的意思是创建一个新的状态,并将旧值更改为新值,这在 Immutable.js 中很常见。

谢谢!

最佳答案

setIn将设置一个新值,这将覆盖您以前的值,您可能需要 mergeIn将新的属性合并到原始值。

var state = Immutable.fromJS([
{"id":0, "url":"http://someUrl", "thumb_url":"http://someUrl", "other_url":"http://someUrl"},
{"id":3, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":1, "url":"http://someUrl", "thumb_url":"http://someUrl", "alternative_url":"http://someUrl"},
{"id":5, "url":"http://someUrl", "thumb_url":"http://someUrl", "yet_another_url":"http://someUrl"}
])

var index = 2;
var new_item = { id: 1, url: 'my_new_url' };
var state = state.mergeIn([index], new_item);
console.log(state.toJS())
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.7.5/immutable.min.js"></script>

关于javascript - 如何更新不可变列表中的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33941577/

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