我有这个状态变量
const [validMonths2019, setValidMonths2019] = useState([])
现在,当选中复选框时,将调用事件处理程序
<Form.Check label='Januar 2019' id='2019' onChange={(event) => handleCheck('01', event)} />
这是事件处理程序
function handleCheck (value, event) {
const months2019 = [...validMonths2019]
if (event.target.id === '2019' && event.target.checked) {
console.log(value) // value is 01
months2019.push(value)
setValidMonths2019(months2019)
} else if (event.target.id === '2019' && !event.target.checked) {
console.log(value) // value is 01
months2019.filter(item => item !== value)
console.log(months2019)// months2019 is still the same array.
setValidMonths2019(months2019)
}
}
过滤器方法没有执行任何操作。数组保持不变。
最佳答案
过滤器不会改变数组,而是返回一个新数组,因此您需要捕获它的值
const myNewArray = months2019.filter(item => item !== value)
console.log(myNewArray) //<-- Here is your filtered array
关于javascript - 未选中复选框时从数组中删除元素(过滤方法不起作用?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61051645/