Javascript 第一次单击后单击复选框的“接头移除”选项
我有一个复选框,需要点击和关闭。但是,在我的函数中,拼接只允许这种情况发生一次,因为一旦用户选中复选框,它就会将其从阵列中删除。如何使复选框可切换Javascript 第一次单击后单击复选框的“接头移除”选项,javascript,reactjs,Javascript,Reactjs,我有一个复选框,需要点击和关闭。但是,在我的函数中,拼接只允许这种情况发生一次,因为一旦用户选中复选框,它就会将其从阵列中删除。如何使复选框可切换 const [supplierAddress, setSupplierAddress] = useState([]); const handleAddressCheck = item => { console.log(item); const itemIndex = supplierAddress.findIndex(supplier
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>
))
}
const[supplierAddress,setSupplierAddress]=useState([]);
const handleAddressCheck=项目=>{
控制台日志(项目);
const itemIndex=supplierAddress.findIndex(supplierItem=>supplierItem.id==item.id);
如果(itemIndex>=0){
设置供应商地址(供应商地址.拼接(itemIndex,1));
}否则{
设置供应商地址(供应商地址.concat([项目]);
}
};
{
sfilteredSuppliers.map(行=>(
{row.name}
{row.companyRegistrationNumber}
{row.vatRegistrationNumber}
{row.website}
supplierItem.id==行.id)}
name=“选中”
color=“primary”
onChange={()=>handleCheckChange(行)}/>
))
}
问题是,不返回更新的数组(删除项目后的数组),它返回已删除的项目,还将改变原始数组。所以不要用更好的来使用
像这样:
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]));
}
};
检查此示例:
a=[1,2,3,4];
设指数=2;
设b=a.拼接(索引,1);
//项目将从阵列中删除
console.log('a',a);
//b将是[3]
console.log('b',b)代码>不要在状态上使用突变。剪接突变数据,并将秘密更改,而不允许重新编码。1。handleCheckChange
不应该是handledresscheck
?2.不应该supplier.find
是supplierAddress.find
?3. splice
返回删除的元素,因此在setSupplierAddress
中使用结果看起来是错误的。嘿,谢谢,这解决了我的问题,但是如果你能将这行代码分解为我setSupplierAddress(supplierAddress.filter(el=>el.id!=item.id));这里到底发生了什么?当然,如果你打断这一行,它将是:let newArr=supplierAddress.filter(el=>el.id!=item.id);设置供应商地址(newArr)代码>,筛选器将在删除该特定项后返回新数组。此外,过滤器不会对原始数组进行更改,它将返回不带该项的新数组。我们传递给setSupplierAddress
的数组将是supplierAddress
的新值。