我试图创建一个删除按钮,以从项目列表中过滤出项目并更新状态变量。
public OnDeleteClick = (): void => {
const selectionCount = this._selection.getSelectedCount();
let newArray = this.state.items;
for (let i = 0; i < selectionCount; i++) {
const keyToBeRemoved = (this._selection.getSelection()[i] as any);
const filteredItem = newArray.filter(item => item !== keyToBeRemoved);
newArray = filteredItem;
}
this.setState({
items: newArray
})
}
这是可行的,但我不想使用for循环。 所以我写了这个。
public OnDeleteClick = (): void => {
let selectedItems = (this._selection.getSelection() as {}[]);
let itemsCopy = this.state.items;
let newArray = itemsCopy.filter(x => x != selectedItems);
this.setState({
items: newArray
})
}
但这不会过滤掉项目。什么不起作用?
答案 0 :(得分:0)
您可以使用indexOf()
函数来检查该项是否存在于selectedItems数组中,并在必要时将其删除。
public OnDeleteClick = (): void => {
let selectedItems = (this._selection.getSelection() as {}[]);
let itemsCopy = this.state.items;
let newArray = itemsCopy.filter(x => selectedItems.indexOf(x) >= 0);
this.setState({
items: newArray
})
}
答案 1 :(得分:0)
您可以使用否定includes或some甚至indexOf的结果,就像在其他答案中一样:
public OnDeleteClick = (): void => {
let selectedItems = (this._selection.getSelection() as {}[]);
this.setState({
items: this.state.items.filter(
item=>!selectedItems.includes(item)
//using some
// !selectedItems.some(
// selected=>
// selected===item
// )
)
})
}