【发布时间】:2020-06-27 03:29:28
【问题描述】:
我正在尝试通过它们的 id 获取图像。后端的架构如下:DB 以二进制形式存储图像,还有一个存储图像 id 的表。
我在前端使用 apollo 客户端来预取图像 ID,然后发送另一组获取请求。
不幸的是我得到Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. 谁能帮我
1)弄清楚它为什么会发生。我看到堆栈中有一堆待处理的承诺。
2) 如何将其重构为更好的架构。
import React, {useState} from 'react'
import {useQuery} from "@apollo/react-hooks";
import {gql} from 'apollo-boost';
const apiEndpoint = 'http://localhost:9211';
const getProductImage = function (id) {
return gql`
{
productById(id: "${id}") {
images {
imageId
}
}
}`
};
const fetchImage = (imageUrl, allImgsArr) => {
return fetch(imageUrl)
.then(res => res.blob())
.then(img => allImgsArr.push(URL.createObjectURL(img)))
};
const ItemPage = (props) => {
const [id] = useState(props.match.params.id);
const {data} = useQuery(getProductImage(id));
let imagesIds = [];
if (data) {
data.productById.images.forEach(image => {
imagesIds.push(image.imageId)
});
}
const [imagesUrls, setImagesUrl] = useState([]);
// MULTIPE FETCH RETRIEVALS START
for (let imId of imagesIds) {
setImagesUrl(imagesUrls => [...imagesUrls, fetchImage(`${apiEndpoint}/image/${imId}`, imagesUrls)]);
}
// MULTIPE FETCH RETRIEVALS END
return (
<>
<div>
<div>
<img src={imagesUrls[0] ? imagesUrls[0] : ''} alt="main item 1 photo"/>
</div>
<div>
<div>
<img src={imagesUrls[1] ? imagesUrls[1] : ''} alt="Additional item 1 photo"/>
</div>
</div>
</div>
</>
)
};
export default ItemPage;
【问题讨论】:
标签: reactjs react-hooks react-apollo apollo-client