[英]How to force update state in ReactJS
I came from here so please don't mark it as a duplicate.我来自这里,所以请不要将其标记为重复。
I'm trying to get every value of mainState
to be placed in anotherState
so at the end I have an array of arrays.我试图将mainState
的每个值都放在anotherState
中,所以最后我有一个 arrays 数组。 mainState
is an changes on hover and it changes a lot so I can't assign every value I have in it to anotherState
, I only need the value when clicked. 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>
However, this doesn't work and even though mainState
updates perfectly everytime, anotherState
is always one step behind.但是,这不起作用,即使mainState
每次都完美更新, anotherState
总是落后一步。 currentItem
represents an array index so I can't click one more time to get the last value of mainState
in anotherState
. currentItem
表示一个数组索引,因此我无法再单击一次以获取mainState
在anotherState
中的最后一个值。 I, using useEffect()
which broke React because hover changes a lot and I ended up with an array of hundreds of values.我使用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)))
}
How can I work around this?我该如何解决这个问题?
setAnotherState is asynchronous. setAnotherState 是异步的。 So if you want to get latest update value of anotherState.因此,如果您想获取另一个状态的最新更新值。
You should use useEffect like你应该使用 useEffect 像
useEffect(() =>
Console.log("anotherState",anotherState)
// Do your stuff
,[anotherState])
This hook will called whenever another state gets updated using setAnotherState.每当另一个 state 使用 setAnotherState 更新时,都会调用此钩子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.