如何从Immutable中的数组中删除对象?

ffx*_*sam 25 javascript immutable.js

鉴于这样的状态:

state = {
  things: [
    { id: 'a1', name: 'thing 1' },
    { id: 'a2', name: 'thing 2' },
  ],
};
Run Code Online (Sandbox Code Playgroud)

如何创建删除ID"a1"的新状态?推送新商品很容易:

return state.set(state.get('things').push(newThing));
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚如何通过其id属性搜索和删除对象.我试过这个:

return state.set('tracks',
  state.get('tracks').delete(
    state.get('tracks').findIndex(x => x.get('id') === 'a2')
  )
)
Run Code Online (Sandbox Code Playgroud)

但它似乎很乱,加上只有找到项目才有效,因为如果findIndex返回-1,那就是有效值delete.

Tus*_*har 34

你可以用Array#filter.

return state.set('things', state.get('things').filter(o => o.get('id') !== 'a1'));
Run Code Online (Sandbox Code Playgroud)

  • 有一点需要注意,即使数组没有匹配的元素,也会返回一个新的不可变的.根据结构的大小,这可能是值得了解的事情,因为它将有效地破坏基于React中的不可变状态比较所做的任何渲染优化. (2认同)
  • 我LOOOOOOOVE这个!!!比循环和拼接容易得多,我再也不会这样做了。 (2认同)

Mus*_*usa 11

当你使用过滤器时,它迭代所有循环 - >一种有效的方法是找到index => slice并使用splitter ...

const index = state.findIndex(data => data.id === action.id);

return [...state.slice(0, index), ...state.slice(index + 1)];
Run Code Online (Sandbox Code Playgroud)


haz*_*ous 5

或者,当您“搜索然后删除”时...

var itemIndex = this.state.get("tracks").findIndex(x => x.get('id') === 'a2');

return itemIndex > -1 ? this.state.deleteIn(["tracks", itemIndex]) : this.state;
Run Code Online (Sandbox Code Playgroud)

这将确保在没有更改时状态不会发生变化。