javascript - 如何在 ReactJS 中强制更新状态
问题描述
我来自这里,所以请不要将其标记为重复。
我试图让每个值都mainState
被放入,anotherState
所以最后我有一个数组数组。mainState
是悬停时的变化,它变化很大,所以我不能将其中的每个值都分配给anotherState
,我只需要单击时的值。
const [mainState, setMainState] = useState([])
const [anotherState, setAnotherState] = useState([])
const [currentItem, setCurrentItem] = useState(0)
//mainState changes on hover and it can change a lot
const onClickHandler = () => {
setAnotherState([...anotherState, mainState])
if (currentItem >= 4) {
// done with this component move to the next component
} else {
setCurrentItem(currentItem + 1)
setMainState([])
}
}
return (
<div onClick={onClickHandler}></div>
但是,这不起作用,即使mainState
每次都完美更新,anotherState
也总是落后一步。currentItem
表示一个数组索引,所以我不能再单击一次来获取 in 的最后一个mainState
值anotherState
。I ,使用useEffect()
which 破坏了 React,因为悬停变化很大,我最终得到了数百个值的数组。
// tried useEffect() like in the question above, ended up with an array of hundreds of values
useEffect(() => setAnotherState([...anotherState, mainState]))
// tried using callback function like in one of the comments which didn't work and remained the same
setAnotherState(() => [...anotherState, mainState])
// another different way not using hooks is I created an empty array constant in the component
// and on click I tried pushing the value of mainState to that array using deep copy
// I keep ending up with the last array pushed only
const arrays = []
const onClickHandler = () => {
arrays.push(JSON.parse(JSON.stringify(mainState)))
}
我该如何解决这个问题?
解决方案
setAnotherState 是异步的。因此,如果您想获取另一个状态的最新更新值。
你应该使用 useEffect 像
useEffect(() =>
Console.log("anotherState",anotherState)
// Do your stuff
,[anotherState])
每当使用 setAnotherState 更新另一个状态时,都会调用此钩子。
推荐阅读
- c++ - g超时在gtk c ++中添加秒数
- javascript - 仅查找嵌套数组中的问题(递归)
- node.js - 发送大于 1 MB 的文件时,Socket.io 用户断开连接
- javascript - React-Select:值未正确显示
- r - 如何在 R 中删除网格线并为 plotly 提供清晰的背景?
- php - 安装我的主题“listeo”时,我找到了这个错误解决方案
- postgresql - postgresql 仅从 JSONB 数据类型中选择一些子键
- c++ - 将 .bin 文件中的二进制数据读取到 C++ 中的结构中
- python - 在 select(query) sqlite3 python 中是否有任何符号或方法可以返回列中的所有数据?
- c - 在 C 中使用链表进行堆栈 - 显示功能不会停止