That's surely because the rooms
state hasn't been updated yet when you console.log
it.
You should keep in mind that useState
is assyncronus, meaning that it's altered value it's not instantly reflected.
If you do:
const handleSubmit = (newRoom) => {
setRooms([...rooms, newRoom])
console.log(rooms)
// Possibly won't get the desired result
}
But as React, when a state is changed, it rerenders. You can put the console.log
anywhere before the return (o render function if it's a class)
const Component = () => {
const handleSubmit = (newRoom) => {
setRooms([...rooms, newRoom])
}
console.log(rooms)
// Possibly you will get the desired result
return (
..your component JSX
)
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…