[英]TypeError: Cannot read properties of undefined (reading 'map') NEXTJS
I am trying to fetch an image from this API by using getStaticProps but I can't seem to get it.我正在尝试使用 getStaticProps 从此 API 获取图像,但我似乎无法获得它。
If I add a '?'如果我添加一个“?” to the code like this then in the log it says 'undefined'.
像这样的代码,然后在日志中显示“未定义”。 Why can't I fetch it?
为什么我拿不到?
<div>
{hotelPics.map((hotelpic)=> (
<Image src={hotelpic.url} />
))}
</div>
import Image from 'next/image';
import React from 'react'
function Images({hotelPics }) {
console.log(hotelPics);
return (
<div>
{hotelPics.map((hotelpic)=> (
<Image src={hotelpic.url}/>
))}
</div>
)
}
export async function getStaticProps() {
const res= await fetch ('https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG')
const hotelPics = await res.json()
return {
props: {
hotelPics,
},
}
}
export default Images
getStaticProps
are "compiling" at build time, so you need to check isFallback
variable getStaticProps
在构建时“编译”,因此您需要检查isFallback
变量
Also, you have nested images
array in hotelPics
array returned from getStaticProps
此外,您在从
getStaticProps
返回的hotelPics
数组中嵌套了images
数组
import Image from 'next/image';
import { useRouter } from 'next/router';
import React from 'react'
function Images({hotelPics}) {
const router = useRouter();
if (router.isFallback) {
return <h1>Loading...</h1>;
}
//console.log(hotelPics.images)
return (
<div>
{hotelPics.map((hotelpic)=> (
hotelpic.images.map((image) => (
//replace here with Image tag
<p key={image.url}>{image.url}</p>
)
)
))}
</div>
)
}
export async function getStaticProps() {
const res= await fetch ('https://obmng.dbm.guestline.net/api/hotels?collection-id=OBMNG')
const hotelPics = await res.json()
return {
props: {
hotelPics,
},
}
}
export default Images
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.