繁体   English   中英

React state 推送到数组时无法正确更新

[英]React state not updating properly when pushing to an array

我一直在摸索这个问题,我想知道为什么我的 state 不会更新。 我已经编写了一个功能组件,我知道我遗漏了一些小东西,但我不知道是什么。

目标是更新一个包含选中框名称的数组(从输入复选框更新)。 这是我的代码

export default function Projects(props) {
  const [checkedBoxes, setCheckedBoxes] = useState([]);

  const onCheck = box => {
    let boxes = [...checkedBoxes];
    console.log(`Checking box ${box}`);
    if (document.getElementById(box).checked) {
      console.log(`Box checked`);
      //Add box
      boxes.push(box);
    } else {
      console.log(`Removing box`)
      //Remove box
      let index = 0;
      for (let i = 0; i < boxes.length; i++) {
        if (boxes[i] === box)
          index = i;
      }
      boxes.splice(index, 1)
    }
    console.log(`Boxes is now ${boxes}`)
    setCheckedBoxes(boxes);
    console.log(`Checked boxes is now: ${checkedBoxes}`)
    console.log(`Boxes length: ${boxes.length}`)
    console.log(`Checked boxes length: ${checkedBoxes.length}`)
}

console.log output如下:

Checking box box1
Box checked
Boxes is now box1
Checked boxes is now: 
Boxes length: 1
Checked boxes length: 0

任何人都可以提供任何关于为什么会发生这种情况的见解(或者让我更好地了解如何存储这些信息?)。 目标是让用户选中复选框,然后根据选中的复选框过滤不同的 state(项目列表)。

谢谢

React state 更新是异步的,因此尝试在设置后立即记录新的 state 只会记录当前的 state。 您可以在 state 更新后使用效果来记录它。 请记住将checkedBoxes添加到依赖数组中,以便仅在更新时调用效果的回调。

export default function Projects(props) {
  const [checkedBoxes, setCheckedBoxes] = useState([]);

  useEffect(() => {
    console.log(`Checked boxes is now: ${checkedBoxes}`)
    console.log(`Checked boxes length: ${checkedBoxes.length}`)
  }, [checkedBoxes]);

  const onCheck = box => {
    let boxes = [...checkedBoxes];
    console.log(`Checking box ${box}`);
    if (document.getElementById(box).checked) {
      console.log(`Box checked`);
      //Add box
      boxes.push(box);
    } else {
      console.log(`Removing box`)
      //Remove box
      let index = 0;
      for (let i = 0; i < boxes.length; i++) {
        if (boxes[i] === box)
          index = i;
      }
      boxes.splice(index, 1)
    }
    console.log(`Boxes is now ${boxes}`)
    console.log(`Boxes length: ${boxes.length}`)
    setCheckedBoxes(boxes);
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM