简体   繁体   English

动态和不断变化的图像 URL 可以与 Next/image 一起使用吗

[英]Can Dynamic and Constantly changing image URL work with Next/image

Can Next/Image use empty string variables for the src that'd get set later via an API? Next/Image 可以为稍后通过 API 设置的 src 使用空字符串变量吗?

I have an image url that I'd retrieve from an API.我有一个从 API 检索的图像 url。 so the image src gets set after runtime.所以图像 src 在运行后被设置。 By default it's an empty string '' and then using SWR later it gets set to the full image url, eg https://i.imgur.com/Thgw1b.png默认情况下,它是一个空字符串'' ,然后使用 SWR 将其设置为完整的图像 url,例如https://i.imgur.com/Thgw1b.png

However, I get a build time error, Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {}但是,我收到构建时错误, Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} despite having src already set. Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {}尽管已经设置了 src。 The same error occurs if src='' as well.如果src=''也会出现同样的错误。

const myComponent = ({imageURL = ''}) => {
  // imageURL starts off as '', then the parent updates that value to a proper image url when the API returns a url value. 

  return (
    <>
      // TODO: Fix build time error saying no src is set, despite being set to '' initially
      <Image src={imageURL} alt='Dynamic Image' layout='responsive'/>
    </>
  );
}

Can Next/Image src images be set fully dynamically? Next/Image src 图像可以完全动态设置吗? Where it starts as an empty string then the src url gets populated later?它从空字符串开始,然后稍后填充 src url?

I've seen some answers suggesting useServerSide Props , but that won't work in my use case as the image url API gives a different image url every X hours (Hence using SWR).我已经看到一些建议useServerSide Props的答案,但这在我的用例中不起作用,因为图像 url API 每 X 小时提供一个不同的图像 url(因此使用 SWR)。 So just loading in once doesn't work.所以只加载一次是行不通的。

Note that using <img> tags works perfectly.请注意,使用<img>标签效果很好。 Initially there's no image, then after the image url gets set to the variable, the img tag loads the image in.最初没有图像,然后在图像 url 设置为变量后,img 标签将图像加载进去。

Try rendering the Image conditionally like so :尝试像这样有条件地渲染Image

return (
    <>
      {imageUrl &&
        <Image src={imageURL} alt='Dynamic Image' layout='responsive'/>
      }
    </>
)

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

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