Trying to update an objects state via the useState hook but it does not seem to be working. Just wondering if anyone can spot what I'm doing wrong here:
This is my useState:
const [selectState, setSelectState] = React.useState({
level1: 0,
level2: 0,
level3: 0,
});
Component where I'm trying to update State:
<Button
onClick={() => setSelectState({ ...selectState, level: 1 })}
selected={selectState === 1}
text="Blue"
/>
I can see couple of problems in your code:
setSelectState({ ...selectState, level: 1 })
- you are updating the level
property but it is not present in the state. So you are adding a new property in the state instead of updating the existing one.
selected={selectState === 1}
- selectedState
is an object. So you are comparing a number with an object and because of strict equality operator ( ===
), the following condition:
selectState === 1
will never evaluate to true
.
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.