我有一个需要选中和关闭的复选框。但是,在我的函数中,一旦用户选择了复选框,它将从数组中删除,则该拼接仅允许发生一次。如何使复选框可切换?
const [supplierAddress, setSupplierAddress] = useState([]);
const handleAddressCheck = item => {
console.log(item);
const itemIndex = supplierAddress.findIndex(supplierItem => supplierItem.id === item.id);
if (itemIndex >= 0) {
setSupplierAddress(supplierAddress.splice(itemIndex, 1));
} else {
setSupplierAddress(supplierAddress.concat([item]));
}
};
{
sfilteredSuppliers.map(row => (
<TableRow key={row.id}>
<TableCell scope="row">{row.name}</TableCell>
<TableCell scope="row">{row.companyRegistrationNumber}</TableCell>
<TableCell scope="row">{row.vatRegistrationNumber}</TableCell>
<TableCell scope="row">{row.website}</TableCell>
<TableCell scope="row">
<Checkbox
checked={supplier.find(supplierItem => supplierItem.id === row.id)}
name="checked"
color="primary"
onChange={() => handleCheckChange(row)} />
</TableCell>
</TableRow>
))
}
答案 0 :(得分:1)
问题是,splice不返回更新的数组(删除项目后的数组),它返回已删除的项目,也将使原始数组发生变化。因此,最好不要使用splice来使用filter。
赞:
const handleAddressCheck = item => {
const itemIndex = supplierAddress.findIndex(supplierItem => supplierItem.id === item.id);
if (itemIndex >= 0) {
// here
setSupplierAddress(supplierAddress.filter(el => el.id != item.id));
} else {
setSupplierAddress(supplierAddress.concat([item]));
}
};
检查此示例:
let a = [1, 2, 3, 4];
let index = 2;
let b = a.splice(index, 1);
// item will be removed from the array
console.log('a', a);
// b will be [3]
console.log('b', b);