简体   繁体   中英

React update state array in useEffect hook

I've read all the questions and answers about setting State on an array in React but none seem to fix my issue.

I initialise my arrays like this:

 const initialStates = {cellStatuses: () =>Array(6).fill(Array(5).fill(status.unguessed)), } const [dailyCellStatuses, setDailyCellStatuses] = useLocalStorage('dailyCellStatuses', initialStates.cellStatuses) const [cellStatuses, setCellStatuses] = useState(initialStates.cellStatuses)

and then later I use an effect to mimic componentDidMount and in that effect I check if the cellStatuses need to be updated

useEffect (() => {
    if (gameMode && playedAlreadyToday(lastPlayedDate)) {
      setBoard(dailyBoard)
      setCellStatuses(dailyCellStatuses)
      console.log(cellStatuses, 'cell statuses')
    } else {
      setBoard(initialStates.board)
    }

The console always logs the old state it never updates with the new dailyCellStatuses that I am trying to set. I have tried cloning the dailyCellStatuses [...dailyCellStatuses] I have tried calling a function in the setter I'm really stuck. Help!

your state is updating fine, your issue is you are console logging the value in the same render cycle,

Console log the value outside useEffect or you can do this

    if (gameMode && playedAlreadyToday(lastPlayedDate)) {
      setBoard(dailyBoard)
      setCellStatuses(dailyCellStatuses)
      console.log(dailyCellStatuses, 'cell statuses')
    } else {
      setBoard(initialStates.board)
    }

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