小编Joh*_*eek的帖子

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

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

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

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

javascript reactjs react-hooks react-functional-component

1
推荐指数
1
解决办法
735
查看次数