首页 > 解决方案 > 图片仅在浏览器调整大小/重排时显示

问题描述

我正在尝试尽可能好地描述以下内容。如果您提出更多问题以使我更接近解决方案或什至问题是什么,我很高兴。

我使用 React-app 设置,使用 Razzle 设置 SSR,使用 Apollo 设置 graphQL。也尝试了与 Nextjs 相同的方法。

/shop导航到/shop/shopdetail后,在浏览器调整大小或导航回/shop并再次进入/shop/shopdetail后,图像首先可见。图片 URL 由/shopdetail中的 GraphQL 查询提供。

调整大小之前 调整大小后

调整大小之前和之后。

但是图像似乎是从开发服务器加载的。

Chrome 开发工具

某些图像在首次渲染时,仅当 SSR 之后的 direkt 具有 MIME 类型的 text/plain 时,这是否正常?

我试过的:

添加代码(处理并获取所有图像的图像组件):

const ImageSrcset = ({ sizes, id, imageFormats, fit, position, data }) => {
  let srcSet = '';
  let srcSetJson = '';
  let singleImg;
  let jsonEmpty = true;

  const {
    mediathek: { backgroundColor, source, data: json }
  } = data;
  const { url: srcBeforeSlice } = source;
  const src = srcBeforeSlice.slice(9);

  // Image processing if JSON with image data from graphQL is empty
  src &&
    sizes.forEach(size => {
      const path = `/api/images/${src}?width=${size}&sizes=[${sizes}]&id=${id}&imageFormats=${imageFormats} ${size}w, `;
      srcSet = srcSet + path;
    });

  // Setting src-set from JSON graphQL data
  if (((json && Object.keys(json)) || {}).length >= 1) {
    jsonEmpty = false;
    json &&
      json.jpg.forEach((image, index) => {
        const line = `/images/${json.dir}/${image.url} ${image.w}w,`;
        index === 0 && (singleImg = `/images/${json.dir}/${image.url}`);
        srcSetJson = srcSetJson + line;
      });
  }

  const fitImage =
    fit === 'contain'
      ? {
          objectFit: 'contain',
          width: '100%',
          height: 'auto'
        }
      : fit;

  return (
    <Main backgroundColor={backgroundColor} fit={fitImage} position={position}>
      {src && jsonEmpty ? (
        // route for image-processing and pipe image back
        <img src={singleImg} srcSet={srcSet} sizes="100vw" alt={src} />
      ) : (
        // route when image URL received from GraphQL
        <img src={singleImg} srcSet={srcSetJson} sizes="100vw" alt={src} /> || null
      )}
    </Main>
  );
};

ImageSrcset.defaultProps = {
  sizes: [320, 640, 768, 1024, 1150, 1366, 1500, 1600, 1750, 1920],
  imageFormats: ['jpg', 'webp'],
  fit: {
    objectFit: 'cover',
    width: '100%',
    height: '100%'
  },
  zIndex: 'auto',
  json: {},
  src: null,
  position: 'absolute'
};

const IMAGE_QUERY = gql`
  query image($id: ID!) {
    mediathek(id: $id) {
      _id
      source {
        url
      }
      backgroundColor
      data
      order
    }
  }
`;

export default graphql(IMAGE_QUERY, {
  options: props => ({ variables: { id: props.id } }),
  props: ({ data }) => ({
    data
  })
})(ImageSrcset);

标签: reactjsimagereact-apollonext.jsserver-side-rendering

解决方案


推荐阅读