异步等待行为不如预期在reactjs [英] async await not behaving as expected in reactjs

查看:63
本文介绍了异步等待行为不如预期在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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