推送到数组时反应状态未正确更新

Joh*_*eek 1 javascript reactjs react-hooks react-functional-component

我已经为此摸不着头脑有一段时间了,我想知道为什么我的状态不会更新。我已经编写了一个功能组件,我知道我缺少一些小东西,但我不知道是什么。

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

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}`)
}
Run Code Online (Sandbox Code Playgroud)

console.log输出如下:

Checking box box1
Box checked
Boxes is now box1
Checked boxes is now: 
Boxes length: 1
Checked boxes length: 0
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Dre*_*ese 5

React 状态更新是异步的,因此在设置后立即尝试记录新状态只会记录当前状态。您可以使用效果来记录更新后的状态。请记住添加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);
  }
Run Code Online (Sandbox Code Playgroud)