简体   繁体   English

如何在从 Api react 获得响应后将多个对象添加到空数组中 react

[英]How to add multiple Objects to an empty array react after getting response from Api react

I am uploding 4 images in response i am getting 4 urls one by one save 4 urls in 4 diffrent objects我正在上传 4 张图片作为回应,我得到了 4 个网址,将 4 个网址保存在 4 个不同的对象中

const [multiStatement, setMultiStatement] = useState([])

const multipStatement = async(e) => {
  const files = e.target.files 
  for (let i = 0; i < files.length; i++) {          
    const url = await uploadStaement(files[i])
    console.log(url)
    setMultiStatement([...multiStatement, {type:"document", frontBack:"front", url:url}])
  }
}
<input type="file" id="file" multiple name="file" onChange={multipStatement} />

Every time through the loop you are overwriting the work you did before.每次通过循环,您都会覆盖您之前所做的工作。 If multiStatement was an empty array when this started, then you first set the state to empty array + object with url 0, then empty array + object with url 1, and so on.如果multiStatement在此启动时是一个空数组,那么您首先将状态设置为空数组 + url 为 0 的对象,然后是空数组 + url 为 1 的对象,依此类推。 At the end, the only one that sticks is empty array + object with the last url.最后,唯一坚持的是空数组 + 带有最后一个 url 的对象。

To fix this, use the function version of setMultiStatement, so you are always working with the latest state:要解决此问题,请使用 setMultiStatement 的函数版本,因此您始终使用最新状态:

setMultiStatement(prev => [...prev, {type:"document", frontBack:"front", url:url}]);

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

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