Leo*_*ibe 3 javascript arrays ecmascript-6 reactjs
我需要在 React 中更新组件状态中的数组。我已经看到了这个问题的几个主题,但到目前为止,他们都在使用扩展运算符向数组添加新项目,但我需要在这样的回调中添加或删除项目:
handleCheck (newStatus, isChecked) {
this.setState({ filterStatus: [...this.state.filterStatus, newStatus] })
}
Run Code Online (Sandbox Code Playgroud)
但这里的问题是它不适用于 isChecked 布尔值变为 false 以将它们从数组中删除的状态
从该数组中添加或删除项目的最佳方法是什么,希望使用扩展运算符?
谢谢
尝试使用 .filter 删除元素。请记住[...array]在使用 .filter 之前复制数组(使用语法),不要更改原始数组:
handleCheck (newStatus, isChecked) {
let newArray = isChecked? // if isChecked is true
[...this.state.filterStatus, newStatus] : // add element
[...this.state.filterStatus].filter(e => e !== newStatus); // remove the elements that are equal to newStatus
this.setState({ filterStatus: newArray})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7117 次 |
| 最近记录: |