【发布时间】:2021-12-03 06:48:56
【问题描述】:
最近发了一个关于这个问题的问题:typeError: Cannot read property 'map' of undefined。
我想使用带有getStaticProps 的组件并将其放入我的pages/index.js,但我不能使用我当前的代码。但是,如果我将此组件作为一个页面 (pages/component.js) 并像另一个页面一样打开,它就会正常工作。
组件Galery.js代码:
import styles from '../styles/galery.module.css'
import Image from 'next/image'
import Link from 'next/link'
import photo from '../public/01.png'
export const getStaticProps = async () => {
const res = await fetch('https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card');
const datas = await res.json();
return {
props: { datas }
}
}
const Galery = ({ datas }) => {
return (
<div className={styles.galeryPage}>
<h1 className={styles.title}>Projetos</h1>
<div className={styles.galery}>
<div className={styles.categoryWrapper}>
<h4 className={styles.subTitle}>Escritório</h4>
<div className={styles.lineWrapper}>
<a className={styles.leftArrow}>❮</a>
<div className={styles.line}>
{datas.map((data) => (
<div className={styles.imageBox}>
<Image src={photo} width={400} height={200} layout="responsive" lazy="true" placeholder="blur" />
<div className={styles.linkContent}>
<span className={styles.name} key={data.id}>{data.name}</span>
<Link href=""><a className={styles.link}>Veja Mais!</a></Link>
</div>
</div>
))}
</div>
<a className={styles.rightArrow}>❯</a>
</div>
</div>
</div>
</div>
);
}
export default Galery;
API 链接:https://my-json-server.typicode.com/Leterinho/PortfolioInteriorDesign/card
这是我想要的结构: Desirable Structure
这是作为页面工作的结构: Structure that works
我应该怎么做才能按计划工作?
【问题讨论】:
-
getStaticProps等数据获取方法只能从页面组件(pages文件夹内的组件)中使用。我建议您在index.js中获取页面级别的数据,并将其传递给您的Galery组件。