【发布时间】:2021-09-25 22:18:13
【问题描述】:
我的代码发生了一些非常奇怪的事情,这没有任何意义。每次我保存/存储一些数据时,它都有一个“延迟”,例如,如果我单击 2 个复选框,当我单击第一个复选框时,没有任何反应,当我单击第二个复选框时,它会获取我单击的第一个复选框的值。让我告诉你:
现在,当我单击选择所有这些但至少不会影响数学(这是最重要的部分)时,也会发生同样的情况:
如果我取消全选,则表明至少保存了所有值:
现在更奇怪的部分是我一个一个地做,然后数学不匹配,因为不是“添加”我首先点击的那个:
这是我的一段代码,我的意思是在技术上可以正常工作,但显然我遗漏了一些东西,如果您需要其他东西,请告诉我:
// "librosnuevos" get updated on the firebase I will not add it cause I think is not necessary
const [librosNuevos, setLibrosNuevos] = useState([]);
const [LibrosID, setLibrosID] = useState([]);
const handleChange = (e, data) => {
const { name, checked } = e.target;
if (checked) {
// if cheked and selectall checkbox add all fileds to selectedList
if (name === "allSelect") {
setLibrosID(librosNuevos);
let x = 0
librosNuevos.map((i) => {
x += i.precio
setTPLibrosNuevos(parseFloat(x).toFixed(2))
})
} else {
// if cheked and specific checkbox add specific field to selectedList
setLibrosID([...LibrosID, data]);
let x = 0
LibrosID.map((i) => {
x += i.precio
setTPLibrosNuevos(parseFloat(x).toFixed(2))
})
}
} else {
// if uncheked and selectall checkbox add remove all fileds from selectedList
if (name === "allSelect") {
setLibrosID([]);
let x = 0
librosNuevos.map((i) => {
x = 0
setTPLibrosNuevos(parseFloat(x).toFixed(2))
})
} else {
// if uncheked and specific checkbox remove specific field from selectedList
let tempuser = LibrosID.filter((item) => item.id !== data.id);
setLibrosID(tempuser);
let x = 0
tempuser.map((i) => {
x += i.precio
setTPLibrosNuevos(parseFloat(x).toFixed(2))
})
}
}
console.log(LibrosID)
};
//Parent Checkbox
<input
type="checkbox"
className="form-check-input"
name="allSelect"
checked={LibrosID?.length === librosNuevos?.length}
onChange={(e) => handleChange(e, librosNuevos)}
/>
//Mapped checkbox-child
{librosNuevos.map((libros, index) => (
<tr key={libros.id || index}>
<td >
<input
type="checkbox"
className="form-check-input"
name={libros.id}
checked={LibrosID.some((item) => item?.id === libros.id)}
onChange={(e) => handleChange(e, libros)}
/>
... some smart code that finish the table
}
请求的 Gif:
这是我尝试该答案后得到的:
现在工作了一半,这仍然是升级,仍然需要使价格正确加起来这是我尝试过的:
useEffect(() => {
console.log(LibrosID);
}, [LibrosID])
useEffect(() => {
console.log(tpLibrosNuevos);
}, [tpLibrosNuevos])
tpLibrosNuevos 是每次我选择一个选项时它应该更新的总价格,但它只会在第一个选项之后更新。也许我的数学在某个地方错了?我仔细检查了一下,好像不是这样……
【问题讨论】:
-
GIF 会更好地可视化问题。
-
不知道你能做到,我一会儿上传一个