[英]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:在你的情况下:
handleAddQualification
handleAddQualification
values
, qualifications
values
, qualifications
setQualifications
to queue as async operationsetQualifications
添加到队列作为异步操作qualifications
again with the same result as from step 3qualifications
,结果与步骤 3 相同setQualifications
setQualifications
之前添加的队列中的任务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.状态更新调用是异步的,您无法通过在更新调用后立即记录来查看它们。
qualifications
toqualifications
设置为interface Qual {
subject?: string;
level?: string;
other?: string
}
const [qualifications, setQualifications] = useState<Qual[]>([]);
useEffect(() => {
console.log({qualifications});
}, [qualifications])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.