[英]How to force update state in ReactJS
我来自这里,所以请不要将其标记为重复。
我试图将mainState
的每个值都放在anotherState
中,所以最后我有一个 arrays 数组。 mainState
是 hover 上的更改,它发生了很大变化,因此我无法将其中的每个值都分配给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
表示一个数组索引,因此我无法再单击一次以获取mainState
在anotherState
中的最后一个值。 我使用useEffect()
破坏了 React,因为 hover 变化很大,我最终得到了数百个值的数组。
// 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])
每当另一个 state 使用 setAnotherState 更新时,都会调用此钩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.