为什么我的状态不会立即在控制台日志中更新 [英] Why does my state not update right away in console log

查看:63
本文介绍了为什么我的状态不会立即在控制台日志中更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习React和React钩子,我有一个问题。我有一个称为房间的状态,其中包含房间对象的数组。我创建了一个添加新房间的组件。您填写一个表单,然后单击提交按钮,它将触发一个函数,其中我使用setRooms([... rooms,newRoom])编辑了状态,同时更新了页面上的房间。由于某种原因,当我尝试将其登录到控制台中时(与第一次编辑房间的onSubmit函数相同),它会显示以前的状态,即使它应该被更新,我也可以告诉它已更新,因为新房间会显示在页面上。



请帮助我理解这一点,我无法绕过它。

解决方案

这肯定是因为当您 console.log时,房间状态尚未更新



您应该记住 useState 是异步的,这意味着它的值已更改,不会立即反映出来。 p>

如果您这样做:

  const handleSubmit =(newRoom)=> {
setRooms([... rooms,newRoom])
console.log(rooms)
// //可能不会获得期望的结果
}

但是作为React,当状态改变时,它会重新渲染。您可以将 console.log 放在返回之前的任何位置(如果是类,则为o渲染函数)

  const组件=()=> {
const handleSubmit =(newRoom)=> {
setRooms([... rooms,newRoom])
}

console.log(rooms
// //可能会得到所需的结果

返回(
..您的组件JSX

}


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.

解决方案

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

这篇关于为什么我的状态不会立即在控制台日志中更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆