取消选中复选框时从数组中删除元素(筛选方法不起作用?)



我有这个有状态变量

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)
} 
}

filter方法没有执行任何操作。数组保持不变。

Filter不会改变数组,而是返回一个新数组,因此您需要捕获它的值

const myNewArray = months2019.filter(item => item !== value)
console.log(myNewArray) //<-- Here is your filtered array

最新更新