gpt4 book ai didi

redux - 如何通过索引获取对象 immutable.js

转载 作者:行者123 更新时间:2023-12-05 03:07:38 25 4
gpt4 key购买 nike

在 Immutable.js 中,我如何通过索引从列表中获取对象并设置属性然后更新整个列表。

状态是一组名为艺术家的对象。

[{ id: 1, selected: false}, { id: 2, selected: false}]

现在我想在索引 0 处设置 selected = true

我试过:

  const artistItem = state.get(action.payload.index).set({ selected: true });
const artists = state.get('artists').set(action.payload.index, artistItem);

如何在不覆盖其他属性的情况下实现这一目标?

最佳答案

如果你的状态真的很像

[{ id: 1, selected: false}, { id: 2, selected: false}]

我相信你想使用 List#update :

let state = Immutable.fromJS([
{id: 1, selected: false},
{id: 2, selected: false}
]);

state = state.update(0, (artist) => artist.set('selected', true));
console.log(state); // [{id: 1, selected: true}, {id: 2, selected: false}]

// Note that this is equivalent to:
state = state.set(0, state.get(0).set('selected'));

但是从你的代码看来你的状态实际上看起来更像

{ artists: [{ id: 1, selected: false}, { id: 2, selected: false}] }

如果是这种情况,您将需要使用 Map#updateIn :

let state = Immutable.fromJS({
artists: [
{id: 1, selected: false},
{id: 2, selected: false}
]
});

state = state.updateIn(['artists', 0], (artist) => artist.set('selected', true));
console.log(state); //{artists: [{id: 1, selected: true}, {id: 2, selected: false}]

// Note that this is equivalent to:
state = state.set(
'artists',
state.get(artists).set(
0,
state.get(artists).get(0).set('selected', true)
));

关于redux - 如何通过索引获取对象 immutable.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960108/

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