异步等待行为不如预期在reactjs

编程入门 行业动态 更新时间:2024-10-23 17:30:47
本文介绍了异步等待行为不如预期在reactjs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有

const [data, setData] = useState([]); const getData = async () => { const { data } = await axios.get('/getData'); setData(data.payload); };

和一个从后端调用handleDelete的按钮

and a button to call handleDelete from the backend

const handleDelete = async () => { checked.forEach(async (element) => { await axios.delete('/deleteData', { data: { data: element }, }); }); await getData(); console.log(data); };

数据从后端删除,我有一些组件依赖于React中的数据,并且由于某种原因,数据没有被更新.该组件未使用新值进行更新.

The data is deleted from the backend, I have components that depends on data in React and for some reason, data is not being updated. The component is not updating with the new values.

有人知道我可能做错了什么吗?任何帮助,我们将不胜感激.

Does anyone know what I might doing wrong? Any help is greatly appreciated.

推荐答案

感谢zero298回答了这个问题.这是由于forEach循环触发了await调用而不是等待.我更改为for..of,现在可以使用了!

Thanks to zero298 for answering this question. It was due to the forEach loop firing the await call and not waiting. I changed to for..of and it's now working!

更多推荐

异步等待行为不如预期在reactjs

本文发布于:2023-11-10 02:17:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574067.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:reactjs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!