首页 > 解决方案 > 如何在 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 的最后一个mainStateanotherState。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)))
}

我该如何解决这个问题?

标签: javascriptreactjs

解决方案


setAnotherState 是异步的。因此,如果您想获取另一个状态的最新更新值。

你应该使用 useEffect 像

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

每当使用 setAnotherState 更新另一个状态时,都会调用此钩子。


推荐阅读