从API动态使用useState和useEffect将数据推送到数组

时间:2020-11-01 21:58:58

标签: react-hooks hook use-effect

我有一个API,它返回诸如“ noOfImages:4”之类的图像数量,并且我用于for迭代并获取值,因为i =“ 0,1,2,3”。我正在传递值我到从那里获取图像src的api调用。问题是每次仅显示最后一个值。

const [productImgSrc, setProductImgSrc]= useState([])
  useEffect(() => {
    for( let i = 0; i <= productData.noOfImages; i ++ ){
      setProductImgSrc(getAllImagesBySeq(productData.prodId,i));
    }
  
}, [productData]);

console.log(productImgSrc,'llllllll')

“ i”作为sequenceid的值传递给getAllImagesBySeq函数。

因此,“ productImgSrc”数组应返回类似下面的内容

https://mycompany.com/GetAppImageBySeq/?id=3&&sequence=0&&vendorId=1
https://mycompany.com/GetAppImageBySeq/?id=3&&sequence=1&&vendorId=1
https://mycompany.com/GetAppImageBySeq/?id=3&&sequence=2&&vendorId=1
https://mycompany.com/GetAppImageBySeq/?id=3&&sequence=3&&vendorId=1

但返回为

https://mycompany.com/GetAppImageBySeq/?id=3&&sequence=3&&vendorId=1

0 个答案:

没有答案