state = { filters: ['all'] }
this.state.filters.includes('humans') ?
this.state.filters.filter(val => val !== 'humans') : this.state.filters.push(dropdown)
我使用的条件是,当我点击一个按钮时,项目('humans')被推到状态,当我再次点击同一个按钮时,我需要从中删除项目('humans')阵列。推送工作正常,我需要帮助删除它。我像上面的代码一样使用过滤器,它不会再次添加到数组中但也不会删除。 提前致谢。
最佳答案
使用:
let index = this.state.filters.indexOf('humans');
if (index !== -1)
this.state.filters.splice(index, 1);
或者你最好按照这种方法来 avoid mutating the state在 react 中:
let array = [...this.state.filters]; // make a separate copy of the array
let index = array.indexOf('humans')
if (index === -1) { // not in the array
array.push('humans');
this.setState({filters: array});
} else { // exists in the array
array.splice(index, 1);
this.setState({filters: array});
}
关于javascript - 从数组中删除特定元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54092167/