Answer the question
In order to leave comments, you need to log in
What's wrong with the state change function?
Hello!
There are three objects corresponding to three buttons. When you click on any of them, the state should be updated. There are 3 states in total.
But the changeState function works through one place, more precisely, it doesn’t work properly. I wanted the function to take the state of the button that I clicked on and increase it by 1 (if it is 2, then reset it to zero).
The function only works once, then the error is:Cannot read property 'map' of undefined
const [states, setStates] = useState([
{ id: 1, state: 0 },
{ id: 2, state: 0 },
{ id: 3, state: 0 }
])
const changeState = ({ id }) => {
setStates(prev => {
prev.map(data => {
if (data.id === Number(id)) {
(data.state === 2) ? data.state = 0 : ++data.state
}
})
})
}
Answer the question
In order to leave comments, you need to log in
setStates(prev => {
prev.map(data => {
if (data.id === Number(id)) {
(data.state === 2) ? data.state = 0 : ++data.state
}
})
})
return prev.map...
if (data.id === Number(id)) {
(data.state === 2) ? data.state = 0 : ++data.state
}
[,,,{},]
data => {
if (data.id === Number(id)) {
return (data.state === 2) ? {...data, state: 0} : {...data, state: data.state + 1}
}
return data
}
() => expression
() => { return expression }
() => ({ someObjectField: ... })
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question