【问题标题】:Multiple fetch requests to retrieve image urls多个获取请求以检索图像 url
【发布时间】: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


    【解决方案1】:

    您的查询应该是一个常量,而不是函数。

    const GET_PRODUCT_IMAGE = gql`
      query getProduct($id:String!) { 
       productById(id: $id) {
          images {
            imageId
          }
        }
      }
    }`
    
    // pass variables like this 
     const {data} = useQuery(GET_PRODUCT_IMAGE, { variables: { id },
     });
    
    

    更多信息:https://www.apollographql.com/docs/react/data/queries/

    【讨论】:

    • 这是一个很好的输入,谢谢!但是 Promise 列表仍在不断增加,我认为是因为我需要以某种方式等待我的 fetch 请求......
    猜你喜欢
    • 1970-01-01
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多