next/image 不使用道具作为图片来源

next/image not working with props as image source

我的 Home 页面通过 props

从我的 strapi cms 发送数据到我的 PostSlider 组件
import React from "react";
import styles from './index.module.scss'
import { AxiosService } from '../utils/axios-service'
import PostSlider from '../components/postSlider/postSlider'

const Home = ({ posts }) => {
  return (
    <div id='contentsWrap' className={styles.dohandsWrap}>
      <PostSlider home={true} posts={posts} />
    </div>
  )
}

export default Home

export async function getStaticProps() {
  const axios = AxiosService.create()
  const res = await axios.get('/archives', {
    params: {
      category: 'news',
      display: true,
      showDoson: true,
      _limit: 5,
      _sort: 'id:DESC'
    }
  })

  return {
    props: {
      posts: res.data,
    },
  }
}

然后我的 postSlider 组件映射数据以填充我的滑块

import React from "react";
import Slider from "react-slick";
import "slick-carousel/slick/slick.css";
import "slick-carousel/slick/slick-theme.css";
import styles from './postSlider.module.scss'
import Link from 'next/link'
import Image from 'next/image'

export default function PostSlider({ home, posts }) {
  var settings = {
    infinite: posts.length > 2 ? true : false,
    autoplay: false,
    speed: 500,
    autoplaySpeed: 3000,
    slidesToShow: 3,
    slidesToScroll: 1,
  };
  return (
    <section className={`${styles.postSlider} postSlider ${home ? styles.postSliderHome : 'postSliderNotHome'} ${posts.length > 2 ? 'postSliderPadding' : ''}`}>
      <Slider {...settings}>
        {posts.map((post) => {
          const date = new Date(post.displayDate);
          return (
            <Link key={post.id} href={`/news/${post.id}`}>
              <a className={styles.postSliderLink}>
                <article>
                  <Image src={post.images[0]?.url} alt={post.images[0]?.alternativeText} width={376} height={190} layout="fixed" />
                </article>
              </a>
            </Link>
          )
        })}
      </Slider>
    </section>
  );
}

我确保在 module.exportsnext.config.js 中包含我的 cdn 地址,但我收到以下错误

Error: Image is missing required "src" property. Make sure you pass "src" in props to the next/image component. Received: {"width":376,"height":190}

如果我删除普通 img 标签的 next/image 组件,一切正常。

我做错了什么?

嗯,你的一篇帖子好像有空 images 数组?

Image 组件需要有 src 属性 而你传递 undefined 而不是。

你可以检查是否至少有一张图片然后渲染它,像这样:

<article>
  {post.images.length > 0 && (
    <Image src={post.images[0].url} alt={post.images[0].alternativeText} width={376} height={190} layout="fixed" />
  )}
</article>

在return之前尝试:

const src = {src: post.images[0]?.url}

然后在return里面:

<Image {...src}    //etc...

有时,<Image /> 标签无法正常工作,并且不接受 src 。尝试在 return 之前定义 URL,然后在 src [=43= 中传递 URL ].

就在return之前:

const url = post.images[0]?.url;

然后你可以添加:

<Image src={url} alt={post.images[0]?.alternativeText} width={376} height={190} layout="fixed" />