简体   繁体   English

如何在 Nextjs 中使用 getStaticProps 加载图像列表?

[英]How to load a list of images using getStaticProps in Nextjs?

I have a bunch of images - 230 images to be exact, that I want to preload using getStaticProps.我有一堆图片——准确地说是 230 张图片,我想使用 getStaticProps 预加载。 However, I don't know how to preload all of them using a for loop, as the end result was undefined when I tried to call it in the console.但是,我不知道如何使用 for 循环预加载所有这些,因为当我尝试在控制台中调用它时,最终结果是未定义的。

export async function getStaticProps() {
 frameCount = 230
 for (let id = 1; id < frameCount; id++) {
  const res = await fetch (`https://${VERCEL_URL}/_next/image?url=%2F${id}.webp&w=1080&q=90`)
  const data = await res.json
 }
 return {
  props: {
   data
  }
 }
}

I am not very experienced in NextJS and this is the first time I tried using a for loop in a getStaticProps to get images being preloaded by the client.我在 NextJS 方面不是很有经验,这是我第一次尝试在 getStaticProps 中使用 for 循环来让客户端预加载图像。 Any help would be appreciated!任何帮助,将不胜感激!

You can use Promise.all :您可以使用Promise.all

export async function getStaticProps() {
  const frameCount = 230;

  const data = [];

  for (let id = 1; id <= frameCount; id++) {
    // add new promise to array
    data.push(fetch(`https://${VERCEL_URL}/_next/image?url=%2F${id}.webp&w=1080&q=90`).then((res) => res.json()));

  }
  
  return {
    props: {
      data: await Promise.all(data), // wait for all images to load
    }
  }
}

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

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