dev*_*_el 13 reactjs strapi next.js nextjs-image
我的Home页面通过以下方式将数据从我的strapicms 发送到我的PostSlider组件props
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,
},
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我的 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>
);
}
Run Code Online (Sandbox Code Playgroud)
我确保包含我的 CDN 地址module.exports,next.config.js但出现以下错误
错误:图像缺少必需的“src”属性。确保将 props 中的“src”传递给
next/image组件。收到:{“宽度”:376,“高度”:190}
如果我删除next/image普通img标签的组件,一切都会正常。
我究竟做错了什么?
Dan*_*ila 15
好吧,你的一篇文章似乎有一个空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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
38970 次 |
| 最近记录: |