ola*_*mii 1 javascript reactjs
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})
Run Code Online (Sandbox Code Playgroud)
then i try to change the states by doing:
setMyState({...myState, bulb1state: false})
//My state is now {bulb1state: false, bulb2state: true }
Run Code Online (Sandbox Code Playgroud)
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 }
Run Code Online (Sandbox Code Playgroud)
I was expecting
{bulb1state: false, bulb2state: false }
Run Code Online (Sandbox Code Playgroud)
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
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42 次 |
| 最近记录: |