简体   繁体   English

反应 setstate 不更新对象数组

[英]React setstate not updating object array

I am trying to update an object array but even though the correct values are passed to the function, the array remains blank.我正在尝试更新一个对象数组,但即使将正确的值传递给函数,该数组仍为空白。 If I try add a second object, then somehow the first one gets added and I'm not sure what I'm doing wrong.如果我尝试添加第二个对象,那么不知何故添加了第一个对象,我不确定我做错了什么。

 const [qualifications, setQualifications] = useState([{}]);

  function handleAddQualification(values: any) {
    console.log(values);

    console.log(qualifications);

    setQualifications((prev) => {
      return [...prev, values];
    });

    console.log(qualifications);
  }

The values that I'm passing get logged correctly and the 2 subsequent logs of qualifications both show an empty array of objects.我传递的值被正确记录,随后的 2 个资格日志都显示了一个空的对象数组。

I simplified the object so in my screen shot I added 'one' and the value logs correctly, but the qualifications array remains blank.我简化了对象,因此在我的屏幕截图中我添加了“一”并且值记录正确,但资格数组保持空白。 If I add a second entry of 'two' then for some reason it adds 'one' to the array.如果我添加第二个 'two' 条目,那么出于某种原因,它会将 'one' 添加到数组中。

Please share some insight as to what is going on here?请分享一些关于这里发生了什么的见解?

添加“一个”

添加“两个”

Here is example how event loop works :)这是事件循环如何工作的示例:)

In your case:在你的情况下:

  1. Calling handleAddQualification调用handleAddQualification
  2. Log values , qualifications日志valuesqualifications
  3. Adding setQualifications to queue as async operationsetQualifications添加到队列作为异步操作
  4. Log qualifications again with the same result as from step 3再次记录qualifications ,结果与步骤 3 相同
  5. Here can works tasks from queue which was added before setQualifications这里可以处理在setQualifications之前添加的队列中的任务
  6. setQualifications updates qualifications setQualifications更新qualifications

Take a look here for better understanding https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop看这里以更好地理解https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

The state update calls are asynchronous and you can't see them by logging just after update call.状态更新调用是异步的,您无法通过在更新调用后立即记录来查看它们。

  1. The first object is empty because you have defined it in your default state and you update your new state using the previous state because of this the empty object always stays as first element in the array.第一个对象是空的,因为您已经在默认状态下定义了它,并且您使用以前的状态更新了新状态,因此空对象始终作为数组中的第一个元素。 To fix this set your qualifications to要解决此问题,请将您的qualifications设置为
interface Qual {
  subject?: string;
  level?: string;
  other?: string
}
const [qualifications, setQualifications] = useState<Qual[]>([]);
  1. if you want to log state whenever it updates use an effect hook, something like this如果您想在每次更新时记录状态,请使用效果钩子,就像这样
useEffect(() => { 
    console.log({qualifications});
}, [qualifications])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM