在Immutable.js中,如何通过索引从列表中获取对象并设置属性,然后更新整个列表。
状态是一个名为artists的对象数组。
[{ 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);
如何在不覆盖其他属性的情况下实现这一目标?
答案 0 :(得分:1)
如果您的州确实看起来像
[{ 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)
));
答案 1 :(得分:0)
修改强>
ImmutableList.set()
返回包含更改的另一个列表。
这是修改项目的正确方法:
const index = action.payload.index
const newArtists = state.set(index, { ...state.get(index), selected: true });
...