简体   繁体   中英

Using useState() with an object as state

I am trying to use the setState react hook and I am trying to make an object of states for different states like this

const [myState, setMyState] = useState({bulb1state: true, bulb2state: true})

then i try to change the states by doing:

setMyState({...myState, bulb1state: false})
//My state is now {bulb1state: false, bulb2state: true } 

which is normal and expected, but when i try to set the other state of the object by doing

setMyState({...myState, bulb2state: false})
//My state now becomes {bulb1state: true, bulb2state: false } 

I was expecting

{bulb1state: false, bulb2state: false } 

What could be the cause? is this normal or is this because of the asynchronous way states work?

My best guess is that you have a function which is closing over an obsolete version of the state. I'd have to see the rest of the code surrounding your use of setMyState to be sure.

Regardless, you should be able to fix it by using the callback version of setMyState to make sure you have the latest state:

setMyState(prevState => ({
  ...prevState, 
  bulb2state: false
});

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