Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

reactjs - Why does my state not update right away in console log

i'm learning React and React hooks and i have a question. I have this state called rooms that contains array of room objects. I created a component that adds a new room. You fill out a form and when a submit button is clicked it fires up a function where I edited the state with setRooms([...rooms, newRoom]) and while it updates the rooms on the page. For some reason when I try to log it in the console (in the same onSubmit function that edited rooms the first time), it shows the previous state, even though it's supposed to be updated and i can tell it's updated, because the new room is displayed on the page.

Please help me understand this, i can't wrap my head around it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
  )
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...