React hooks - 将数组重新初始化为空

React hooks -to reinitialise array to empty

我确实有一种状态写成

const[checkboxIds,setCheckboxIds]=useState([])

我有一个 useEffect 作为


useEffect(()=>{
    if (!isEmpty(currentData)) {
      currentData.forEach(id => {
        checkboxIds.push(id);
      });
      setCheckboxIds(checkboxIds);
    }
},[currentData])

并且我将计数显示为 {checkboxIds} 并且显示正确

同样,我确实有 4 个选项卡,例如字母表、颜色、动物和汽车,当我单击每个选项卡时 当前数据 发生变化,因此 checkboxIds 计数也应该发生变化。它在变化,但它也在增加以前的计数

例如,如果我确实有 10 个字母对象,它在初始页面加载时显示计数为 10,当我单击颜色(它有 5 个对象)时,它显示计数为 15(它应该只显示 5 ) 当我点击动物时(它有 10 个对象),它显示计数为 25(它应该显示它的计数为 10)

所以我知道应该在某个地方重新启动 setCheckboxIds,但对我来说它不起作用

我认为您需要将 useEffect 更新为

useEffect(()=>{
    if (!isEmpty(currentData)) {
      const updatedCheckboxIds = [];
      currentData.forEach(id => {
        updatedCheckboxIds.push(id);
      });
      setCheckboxIds(updatedCheckboxIds);
    }
},[currentData])

这种方式在每个效果上都会创建一个新的 checkboxIds 数组并将 id 推入其中。