简体   繁体   中英

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 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.

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. currentItem represents an array index so I can't click one more time to get the last value of mainState in anotherState . I, using useEffect() which broke React because hover changes a lot and I ended up with an array of hundreds of values.

// 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. So if you want to get latest update value of anotherState.

You should use useEffect like

useEffect(() => 
Console.log("anotherState",anotherState)
// Do your stuff 
,[anotherState])

This hook will called whenever another state gets updated using setAnotherState.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM