在用于设置状态的同一函数中访问最新的状态值

Access latest state value in the same function that is used to set the state

我的州

const [selectedRows, setSelected] = useState([])

const handleRowClick = useCallback((id) => {
       if(selectedRows.includes[id]) {
           arr = selectedRows.filter((item) => item !== id) // <==Trying to access the state here
           setSelected((prev) => [arr])
       } else {
          setSelected((prev) => [id])
       }    
})

每次我尝试访问 handleRowClick 函数中的 selectedRows 时,它只是 returns 它的默认值,即。空数组

您没有为 useCallback 使用依赖项数组。你可能想要这个:

const handleRowClick = useCallback((id) => {
       if(selectedRows.includes[id]) {
           arr = selectedRows.filter((item) => item !== id) // <==Trying to access the state here
           setSelected((prev) => [...arr])
       } else {
          setSelected((prev) => [...id])
       }    
}, [selectedRows])

注意:请注意,我正在解构数组,因此您将获得数组的新副本,而不是只有一个元素的数组。