为什么复选框中有更新状态延迟,React

Why there's a update state delay in checkbox, React

我的代码发生了一些非常奇怪的事情,这没有任何意义。每次我 save/store 一些数据都有一个“延迟”,例如,如果我单击 2 个复选框,当我单击第一个时没有任何反应,当我单击第二个时,它会获取我单击的第一个复选框的值.让我告诉你:

现在,当我点击 select 所有这些但它至少不会影响这里的数学(这是最重要的部分)时发生同样的情况:

如果我取消select all 它表明至少保存了所有值:

现在更奇怪的是,如果我一个一个地做,那么数学不匹配,因为没有“添加”我先点击的那个:

这是我的一段代码,我的意思是技术上可以工作,但显然我遗漏了一些东西,如果您需要其他东西,请告诉我:


// "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 是每次我 select 一个选项时它应该更新的总价,但它只在第一个选项之后更新。也许我的数学某处有误?我仔细检查了一下,似乎不是这样...

这不一定是延迟。 setState 是一个异步函数,这意味着,由于您在设置状态后立即登录到控制台,因此您无法确定它是否已完成。

您可以使用具有 state 作为依赖项的 useEffect 检查您的状态。

像这样:

useEffect(() => {
   console.log(LibrosID, librosNuevos);
}, [LibrosID, librosNuevos])

这是一个回调,根据定义,只有在 LibrosIDlibrosNuevos 被更改后才会 运行。

您可以阅读更多相关内容here